gpt4 book ai didi

jQuery:根据屏幕宽度更改元素位置

转载 作者:太空宇宙 更新时间:2023-11-04 10:45:35 24 4
gpt4 key购买 nike

如何在调整屏幕大小时实时改变元素位置?

例如,如果屏幕最初大于 500 像素,则元素应位于 x 位置,否则如果我调整屏幕大小并使其变小,则元素应重新定位。这必须在不按按钮的情况下进行。

jsfiddle:https://jsfiddle.net/zjgrmf24/2/

HTML:

<body>
<div class="change_offset">
reposition
</div>
<div class="here">
move here
</div>
</body>

CSS:

.here {
margin-top:200px;
margin-left:100px;
}
.change_position {
position: absolute;
}

JS:

$(document).ready(function(){
herePos = $('.here').offset();
change = $('change_offset');

if($('body').width() < 500)
{
change.css({
left: herePos.left + "px",
top: herePos.top + "px"
})
}
else
{
change.css({
left: 'auto',
top: 'auto'
})
}
})

最佳答案

使用resize事件:

function handleResize() {
herePos = $('.here').offset();
change = $('change_offset');

if($('body').width() < 500)
{
change.css({
left: herePos.left + "px",
top: herePos.top + "px"
})
}
else
{
change.css({
left: 'auto',
top: 'auto'
})
}
}
$(document).ready(handleResize);
$(window).on("resize", handleResize);

注意:您的代码正在成为 The Horror of Implicit Globals 的牺牲品。 .声明您的变量。

关于jQuery:根据屏幕宽度更改元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35429728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com