jQuery从数据属性获取路径

时间:2022-05-14 20:34:29

I have a small problem, I want to get "path" from data attribute and add to background.

我有一个小问题,我想从数据属性获取“路径”并添加到后台。

HTML

<div>
  <div data-image="../images/header.jpg"></div>
</div>

jQuery

$('[data-image]').css(
    {
        background: "url("+$(this).data('image')+") no-repeat center",
        backgroundSize: "cover",
        height: ($(document).height()/ 3)
    }
);

Do you have any idea how do this?

你知道这是怎么回事吗?

1 个解决方案

#1


2  

Just cache the element in a variable and use it

只需将元素缓存在变量中并使用它即可

var elm = $('[data-image]'); // cache it
elm.css({
    background: "url("+ elm.data('image') +") no-repeat center", // use it
    backgroundSize: "cover",
    height: ($(document).height()/ 3)
});

If there are more elements, you could use each

如果有更多元素,您可以使用每个元素

elm.each(function(){
    $(this).css({
        background: "url("+ $(this).data('image')+ ") no-repeat center",
        backgroundSize: "cover",
        height: ($(document).height()/ 3)
    });
});

#1


2  

Just cache the element in a variable and use it

只需将元素缓存在变量中并使用它即可

var elm = $('[data-image]'); // cache it
elm.css({
    background: "url("+ elm.data('image') +") no-repeat center", // use it
    backgroundSize: "cover",
    height: ($(document).height()/ 3)
});

If there are more elements, you could use each

如果有更多元素,您可以使用每个元素

elm.each(function(){
    $(this).css({
        background: "url("+ $(this).data('image')+ ") no-repeat center",
        backgroundSize: "cover",
        height: ($(document).height()/ 3)
    });
});