如何更改页面调整大小时的左侧属性(jQuery)
我的代码遇到了一些小问题。我想做的是根据当前左值的差异以及页面调整大小的量来更新这些元素的 css 属性“left”。这样,当页面调整大小并且背景移动时,元素也会移动。看一下下面的代码,我将描述这个问题:
$(window).resize(function() {
var docWidth = $(window).width();
if (docWidth < 1000) {
var difference = 1000-docWidth;
$('#headNav a,#icons div').each(function() {
var left = $(this).position().left;
var newLeft = left - difference;
$(this).css({ 'left' : newLeft });
});
}
});
所以我遇到的问题是元素被赋予了通配数的左值,而变量“newLeft”的值是合理的期望值。我认为每个函数正在收集这些值的总和,并为每个元素运行它们 x 找到的元素存在的次数(所以如果有 5 个元素,它会运行 5 次,我的意思是。)我想要的是执行这段代码每个元素都是唯一的,但每个元素只有一次,而不是每个元素 10 次! (这就是 html 中有多少个元素)。
所以我的问题是,如何实现这一目标?我希望我能够很好地解释自己,这很难重复。非常感谢任何帮助。谢谢你!
I'm having slight troubles with my code. What I'm trying to do is make these element's css property 'left' update according to the difference of it's current left value, and the amount the page resizes. This way, when the page resizes and the background moves over, the elements will move too. Take a look at the code below and I'll describe the issue:
$(window).resize(function() {
var docWidth = $(window).width();
if (docWidth < 1000) {
var difference = 1000-docWidth;
$('#headNav a,#icons div').each(function() {
var left = $(this).position().left;
var newLeft = left - difference;
$(this).css({ 'left' : newLeft });
});
}
});
So the issue that I'm getting is the elements are being given left values of wild numbers, while the value of the variable 'newLeft' is the reasonable, desired value. The each function I think is collecting the sums of these values and running them for each element x amount of times that the elements found exist (so if there's 5 elements it runs 5 times, I mean.) What I want is this code to execute uniquely for each element, but just once each, not each element 10 times! (that's how many elements are in the html).
So my question is, how can this be achieved? I hope I explained myself well enough, this was tough to iterate. Any help is extremely appreciated. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有一个有趣的技巧:在
.css()
调用中包含+=
:jQuery 会为您进行数学运算以获得新值。
Here's a fun trick: Include
+=
in your.css()
call:jQuery does the math for you to get the new value.
试试这个:
Try this: