javascript - 使用自定义 attr 添加 css?

标签 javascript jquery

我使用的是带有一点 CSS3 动画的通用 CSS 横幅代码(不是重点,而是提供背景)。我想要实现的是使用自定义属性设置横幅类并获取该属性内容并使用 jQuery 附加样式?就像这样,但是他们的很多 div 将在同一页面上使用相同的技术......

<div class="banner banner-small animate" data-bg="https://domain.com/path/img/bg.png">
    ....
</div>

然后 jQuery 将运行并输出代码,例如...

<div class="banner banner-small animate" data-bg="https://domain.com/path/img/bg.png" style="background-image: url('https://domain.com/path/img/bg.png')">
    ....
</div>

我希望这不是含糊不清。我最近才开始学习 jQuery,我很喜欢它!只是真的不知道如何去做这件事。

最佳答案

当然,您可以通过多种方式使用数据属性作为选择器,然后通过 data() 访问其数据。功能:

// Iterate through each element with the data-bg attribute
$('[data-bg]').each(function(){
     // Set the background image for each element to it's respective
     // attribute value
     $(this).css('background-image','url(' + $(this).data('bg') + ')');
});

或者,如果您不想调用 jQuery 两次,可以使用 Niet的建议:

$('[data-bg]').each(function(){
     this.style.backgroundImage = url(' + this.getAttribute('data-bg') + ')';
});

或者来自adeneo的以下一个,它完全放弃了显式循环:

$('[data-bg]').css('background-image', function() {
     return 'url(' + $(this).data('bg') + ')';
});

关于javascript - 使用自定义 attr 添加 css?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36654459/

相关文章:

javascript - Titanium appcellerator 上的句柄如何无法到达主机

javascript - 如何隐藏除特定 block 之外的所有内容? (JavaScript)

javascript - 服务器发送事件有哪些好的用例

javascript - 多页打印表格数据

javascript - 使用 2 种不同的 body 背景颜色

javascript - 在javascript中打印/警告数组

javascript - 如何更改点击类?

javascript - 在选择框中动态选择多个选项

javascript - 如何显示元素的一部分,并在单击时切换到所有元素?

javascript - 在服务器上创建 AJAX/JSON 回调函数