jQuery动态更改元素高度
我正在做一个流体布局项目。我的文档中有一些固定高度的div,它们的高度都不同。我需要在浏览器调整大小时按比例更改这些div的高度。这是标记jQuery动态更改元素高度,jquery,height,window-resize,Jquery,Height,Window Resize,我正在做一个流体布局项目。我的文档中有一些固定高度的div,它们的高度都不同。我需要在浏览器调整大小时按比例更改这些div的高度。这是标记 <body> <div id="a" class="target"></div> <div id="b" class="target"></div> <div id="c" class="target"></div> </body> })) 当用户重新加载页面
<body>
<div id="a" class="target"></div>
<div id="b" class="target"></div>
<div id="c" class="target"></div>
</body>
}))
当用户重新加载页面时,此脚本可以完美地工作。
当用户在不重新加载的情况下调整浏览器的大小时,我如何通过友好方式获得相同的结果?
我知道我应该应用$(窗口)。调整事件侦听器的大小。但问题是,DIV的初始高度将在比赛中计算,结果将像无休止的循环一样巨大——也就是说,最终高度将以巨大的速度增加或减少。我不需要那个!
如何在事件函数外部进行每个DIV初始高度计算,然后在事件函数内部使用这些高度?或者可能还有另一种方法可以获得相同的结果?看看可以用jquery绑定的resize事件
结束调整大小功能并订阅窗口调整大小事件
$(document).ready(function(){
//set the initial body width
var originalWidth = 1000;
resizeTargets();
$(window).resize(resizeTargets);
});
function resizeTargets()
{
$(".target").each(function()
{
//get the initial height of every div
var originalHeight = $(this).height();
//get the new body width
var bodyWidth = $("body").width();
//get the difference in width, needed for hight calculation
var widthDiff = bodyWidth - originalWidth;
//new hight based on initial div height
var newHeight = originalHeight + (widthDiff / 10);
//sets the different height for every needed div
$(this).css("height", newHeight);
});
}
您需要存储每个div的原始高度。有不同的方法可以做到这一点,这里有一个技巧,将其存储在DOM节点本身(有更好的方法,但这种方法既快又脏)
使用.data将div的初始大小存储在$.each函数中
$(this).data('height', $(this).height());
$(this).data('width', $(this).width());
您可以稍后在resize回调中检索旧尺寸
var old_height = $(this).data('height');
var old_width = $(this).data('width');
希望这有助于真正快速简便的解决方案。工作完美。谢谢无法使用.data使其工作。但这可能是我的错,我几乎没有javascript经验。无论如何,谢谢你。
$(document).ready(function(){
//set the initial body width
var originalWidth = 1000;
/*I need to go through all target divs because i don't know
how many divs are here and what are their initial height*/
function resize() {
//This will only set this._originalHeight once
this._originalHeight = this._originalHeight || $(this).height();
//get the new body width
var bodyWidth = $("body").width();
//get the difference in width, needed for hight calculation
var widthDiff = bodyWidth - originalWidth;
//new hight based on initial div height
var newHeight = this._originalHeight + (widthDiff / 10);
//sets the different height for every needed div
$(this).css("height", newHeight);
}
$(".target").each(resize);
$(document).resize(function(){
$(".target").each(resize);
});
});
$(this).data('height', $(this).height());
$(this).data('width', $(this).width());
var old_height = $(this).data('height');
var old_width = $(this).data('width');