gpt4 book ai didi

javascript - jquery 子选择器不起作用?

转载 作者:行者123 更新时间:2023-11-30 08:38:57 25 4
gpt4 key购买 nike

我有这个代码

$(".cloud").each(function(index, element) {
var x = (Math.random() * 80) + 1;
var y = (Math.random() * 80) + 1;
if (!$(this).attr('id')) {
$(this).css("top", y + '%');
$(this).css("left", x + '%');
$(this).children('a').css("top", y + '%');
$(this).children('a').css("left", x + '%');
}
});

我试图将我的云图片,即具有 .cloud 类的图片(以及应该位于其顶部的 href 文本)移动到随机位置。但是,a href 文本应该在云端。所以我想做的是,我迭代每个具有 .cloud 类的元素,然后也尝试设置其子元素的 CSS。但我只移动了云,而不是 a href 文本。我在这里缺少什么?

这是我的标记:

<section>
<div style="height:100%; width: 100%">
<img src="cloud.png" class="cloud"> <a href="#contact" id="contact" class="cloud">contact</a></img>
<img src="cloud.png" class="cloud"> <a href="#about" id="about" class="cloud">about</a></img>
<img src="cloud.png" class="cloud"> <a href="#work" id="work" class="cloud">work</a></img>
<img src="cloud.png" class="cloud"> </img>
<img src="cloud.png" class="cloud"> </img>
</div>

</section>

最佳答案

img元素不允许有 child ——它们是“自关闭”标签,你应该这样写:

<img src="cloud.png" class="cloud" />

那么你的链接是兄弟元素,因此你应该使用next()方法而不是 children()

$(this).next('a').css({
"top" : y + "%",
"left" : x + "%"
});

作为旁注,您可以指定一个具有所有 CSS 属性的对象,并节省对 jQuery 的一些额外调用。函数,所以代码变为

var cssprops = {
"top" : y + "%",
"left" : x + "%"
};

$(this).css(cssprops).next('a').css(cssprops);

作为最后的旁注,尝试优化代码,您可以使用无序列表而不是 div并将每一对“图像链接”包装成一个列表项;那么您可以将 css 属性仅分配给 <li>元素

关于javascript - jquery 子选择器不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28605147/

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