https://jsfiddle.net/basickarl/apts370w/1/
我希望checkOverflow
函数在这种情况下返回true
。
HTML:
<div style="float:right;">
<div id="z">
<div id="txt">
345345345345345345345345345345345
</div>
</div>
</div>
使用Javascript:
console.log(checkOverflow(document.getElementById('z')));
function checkOverflow(el) {
var curOverflow = el.style.overflow;
if (!curOverflow || curOverflow === 'visible')
el.style.overflow = 'hidden';
var isOverflowing = el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
};
CSS:
div#z {
position: relative;
background: red;
width: 50px;
height: 50px;
overflow: auto;
}
div#txt {
background: lightblue;
float: right;
}
知道为什么函数的console.log
会在这里返回true
吗?
答案 0 :(得分:2)
scrollHeight
和scrollWidth
对应于实际的clientHeight
和clientWdith
+隐藏的高度或宽度。由于div#txt
向右浮动,因此不会溢出。
您应该查看box model和this answer。
答案 1 :(得分:1)
问题是#txt
向右浮动,所以它向左溢出。
但是默认的左右方向无法向左滚动。
但是,如果您使用从右到左的方向,则可以
#z { direction: rtl; }
function checkOverflow(el) {
var curOverflow = el.style.overflow;
if (!curOverflow || curOverflow === 'visible')
el.style.overflow = 'hidden';
var isOverflowing = el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
}
console.log(checkOverflow(document.getElementById('z')));
&#13;
div#z {
position: relative;
background: red;
width: 50px;
height: 50px;
overflow: auto;
direction: rtl;
}
div#txt {
background: lightblue;
float: right;
}
&#13;
<div style="float:right;">
<div id="z">
<div id="txt">
345345345345345345345345345345345
</div>
</div>
</div>
&#13;
当然,如果内容向右溢出(例如,您更改为float: left
),则会遇到同样的问题。
如果您想要更通用的方法,可以使用getBoundingClientRect
:
var rect = el.getBoundingClientRect();
var isOverflowing = [].every.call(el.children, function(child) {
var childRect = child.getBoundingClientRect();
return childRect.left < rect.left
|| childRect.right > rect.right
|| childRect.top < rect.top
|| childRect.bottom > rect.bottom;
});
function checkOverflow(el) {
var curOverflow = getComputedStyle(el).overflow;
if (!curOverflow || curOverflow === 'visible')
el.style.overflow = 'hidden';
var rect = el.getBoundingClientRect();
var isOverflowing = [].every.call(el.children, function(child) {
var childRect = child.getBoundingClientRect();
return childRect.left < rect.left
|| childRect.right > rect.right
|| childRect.top < rect.top
|| childRect.bottom > rect.bottom;
});
el.style.overflow = curOverflow;
return isOverflowing;
}
console.log(checkOverflow(document.getElementById('z')));
&#13;
div#z {
position: relative;
background: red;
width: 50px;
height: 50px;
overflow: auto;
}
div#txt {
background: lightblue;
float: right;
}
&#13;
<div style="float:right;">
<div id="z">
<div id="txt">
345345345345345345345345345345345
</div>
</div>
</div>
&#13;
答案 2 :(得分:0)
这是我的解决方案
https://jsfiddle.net/apts370w/3/
问题是,如果你更改为span标签,它不是内联元素
我也改变了这个
el.offsetWidth //instead of clientWidth