长话短说,我正在构建一个工具,以便在响应式网站上不适合时隐藏表格。我遇到了一个奇怪的错误,我希望有人能阐明。当表格被隐藏时,jQuery突然决定在其宽度上增加20px。这阻止了我进行计算以在屏幕再次变宽时重新显示表格。我将把代码放在下面,但请查看jsFiddle以更好地了解正在发生的事情:
http://jsfiddle.net/kthornbloom/mSAxJ/1/
// Check if table is too big for viewport.
function tableChecker() {
$(".rwd-table").each(function () {
var wrapWidth1 = parseInt($(this).parent().width()),
tableWidth = parseInt($(this).outerWidth());
$('#debug').html('<font color="red">Wrapper Width:</font> ' + wrapWidth1 + 'px <font color="blue">Table Width:</font>' + tableWidth + 'px');
if (wrapWidth1 < tableWidth) {
var finaltableWidth = $(this).outerWidth();
$(this).next('.viewtable').show();
$(this).hide();
}
});
}
// Call on page load and page resize
tableChecker();
$(window).resize(function () {
tableChecker();
});
顺便说一下,我正在Chrome 31中查看此内容。
好吧,在永远搞砸了这个之后,我决定这是一个当你尝试测量隐藏物体的宽度时发生的错误。我的解决方法是让对象保持可见,并将其放入高度:0 和溢出:隐藏的容器中。这将提供正确的宽度。
认为我有东西给你,看起来当一个元素display: none;
该查询在后台做一些额外的事情,允许它"猜测"高度/宽度
相关: jQuery: height()/width() 和 "display:none"
除非元素具有特定大小,否则 hide() 会将其宽度/高度设置为 auto,然后它必须猜测这些大小。
运行此小提琴并查看 chrome 开发工具和控制台小提琴:http://jsfiddle.net/Culyx/aN6x7/2/
.CSS:
#one{
background-color: red;
height: 50px;
width: 50px;
}
#two{
background-color: blue;
}
#clickMe{
background-color: green;
height: 50px;
width: 50px;
}
.JS:
console.log($("#one").height());
console.log($("#one").width());
console.log($("#two").height());
console.log($("#two").width());
$("#clickMe").click(function(){
$("#one").hide();
$("#two").hide();
console.log("Now they're hidden");
console.log($("#one").height());
console.log($("#one").width());
console.log($("#two").height());
console.log($("#two").width());
});
.HTML:
<div id="one">Hello</div>
<div id="two">Hello</div>
<div id="clickMe">Click Me</div>