gpt4 book ai didi

javascript - 如何更改页面 Load "jquery"属性中给出的 Divs CSS 背景

转载 作者:行者123 更新时间:2023-11-29 14:43:10 25 4
gpt4 key购买 nike

所以基本上我遇到了这个问题,我希望 jQuery 检查属性中的类 .js-bg:"data-background",获取属性并然后将该 div css 背景更改为属性中给定的 url。

HTML:

<div class="js-bg">
<br><br><br><br>
</div>

CSS:

.js-bg {
width: 100%;
background-size: cover;
background-position: center;
}

JS/jQuery(第一次尝试):

var item = $('.js-bg'),
bg = item.attr('data-background');

item.css('background', 'url(' + bg + ')');

这里的问题是它采用第一个属性,然后将该图像应用到所有其余的 Div。

JS/jQuery(第二次尝试):

var item = $('.js-bg'),
bg = item.attr('data-background');

item.load(function() {
$(this).css('background', 'url(' + bg + ')');
});

但这也行不通,我在整个互联网上搜索过,但找不到答案。

感谢您的考虑。

最佳答案

尝试遍历这些元素并像这样为每个元素设置背景:

$('.js-bg').each(function(){

var bg=$(this).attr('data-background');
$(this).css('background', 'url('+ bg +')');

});

关于javascript - 如何更改页面 Load "jquery"属性中给出的 Divs CSS 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35950853/

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