检测div何时溢出 [英] Detecting when a div overflows

查看:108
本文介绍了检测div何时溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据屏幕的大小让我的网站流动。我创建了这个: http://jsfiddle.net/aboveyou00/7NeZz/1/ 。它工作得很好。这两个内部div在同一行中居中并且彼此相邻,当它们合适时 - 但是当它们不合并时,它们都按照它们自己的路线居中。



<这是HTML。

 < div class =divContainer> 
< div class =div1>
< img src =http://placehold.it/200x300/EEEEEE/000000/>
< / div>
< div class =div2>< / div>
< / div>

问题是,现在我试图弄清楚如何为 div2 根据是否被推送到下一行而改变。如果它在同一行上,则内部文本应该与左侧对齐。如果它被移动到底部,那么内部文本应该居中对齐。



约束:如果需要,我可以使用javascript和jQuery。一个纯CSS的解决方案是首选,但不是预期的。



我该如何做?

解决方案

不完全确定我理解你的问题,但如果没有围绕上述内容并且宽度已修复的内容,则可以使用相当平凡的媒体查询来更改第二个div的样式。

  @media all and(max-width:520px){
div.div2 {
text-align:center;
}
}

http://jsfiddle.net/ExplosionPIlls/7NeZz/2/



如果你不知道宽度或是否有更复杂的事情发生,你可以在调整大小时将两个div的合并宽度与容器进行比较。

 ($(。div1)。width()+ $(。div2)。width()函数调用函数function(){
。 > $(。divContainer).width()){
$(。div2).css('text-align','center');
}
else {
$(。div2).css('text-align','left');
}
});

$(window).trigger('resize');

http://jsfiddle.net/ExplosionPIlls/7NeZz/3/

I'm trying to make my website flow depending on the size of the screen. I created this: http://jsfiddle.net/aboveyou00/7NeZz/1/. It is working well enough. The two inside divs are centered and next to each other on the same line, when they fit - but when they don't, they're centered each on their own line.

Here's the HTML. The CSS and JavaScript are in the fiddle.

<div class="divContainer">
  <div class="div1">
    <img src="http://placehold.it/200x300/EEEEEE/000000" />
  </div>
  <div class="div2"></div>
</div>

The problem is, now I'm trying to figure out how to make the formatting for div2 change depending on whether or not it was pushed to the next line. If it is on the same line, then the inside text should be aligned to the left. If it was moved to the bottom, then the inside text should be center-aligned.

Constraints: I can use javascript, and jQuery, if needed. A CSS-only solution is preferred, but not expected.

How do I do this?

解决方案

Not completely sure that I understand your question, but if there is no content surrounding the above and the widths are fixed, you can use a fairly trivial media query to change the style of the second div when the container gets too small.

@media all and (max-width: 520px) {
    div.div2 {
        text-align: center;
    }
}

http://jsfiddle.net/ExplosionPIlls/7NeZz/2/

If you don't know the widths or if there is more complicated stuff going on, you can compare the combined widths of the two divs to the container on resizing.

$(window).on('resize', function () {
    if ($(".div1").width() + $(".div2").width() > $(".divContainer").width()) {
        $(".div2").css('text-align', 'center');
    }
    else {
        $(".div2").css('text-align', 'left');
    }
});

$(window).trigger('resize');

http://jsfiddle.net/ExplosionPIlls/7NeZz/3/

这篇关于检测div何时溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆