我正在使用bxslider滑块编写一些代码,因为我有很多大的图像,页面加载缓慢,我尝试了任何lazy loading plugin,但与bxslider不太兼容。最后,我试着自己写一些代码。
我试着做一些事情,如果div is visible,removeAttr data-style,然后添加addAttr style。我在小提琴中的代码(bxslider的汇出代码):
<div class="bgAnchor" data-style="background:url('http://it.bing.com/az/hprichbg?p=rb%2fNewRiverGorgeBridge_ROW468427072.jpg') no-repeat;background-position:0px 0px;"></div>
<div class="bgAnchor" data-style="background:url('http://it.bing.com/az/hprichbg?p=rb%2fPalmFrond_ROW2095872384.jpg') no-repeat;background-position:0px 0px;"></div>
<div class="bgAnchor" data-style="background:url('http://it.bing.com/az/hprichbg?p=rb%2fJacksonSquare_ROW1364682631.jpg') no-repeat;background-position:0px 0px;"></div>
<div class="bgAnchor" data-style="background:url('http://it.bing.com/az/hprichbg?p=rb%2fAustraliaClouds_ROW1600390948.jpg') no-repeat;background-position:0px 0px;"></div> $('.bgAnchor').each(function(){
if($(this).is(":visible")){
var data_style = $(this).attr('data-style');
if(data_style!== 'undefined' && data_style!== false){
var attr_image = $(this).attr("data-style");
$(this).css('background',attr_image).removeAttr("data-style");
}
}
});但我不知道为什么不是工作。如果有人能帮我,我很高兴。非常感谢。
发布于 2012-02-23 17:24:48
来自jQuery css()页面
Shorthand CSS properties (e.g. margin, background, border) are not supported.
For example, if you want to retrieve the rendered margin,
use: $(elem).css('marginTop')
and $(elem).css('marginRight'), and so on.--这意味着您不能在css()中使用背景
因此,您必须使用样式属性来完成它。
$(this).attr('style',attr_image);这是jsFiddle页面
发布于 2012-02-23 17:15:23
.css()一次只对一个属性工作,得到3,尝试使用data_style属性;未定义不是字符串,它是内置变量;不需要获得两次data_style。
试试这个:
$('.bgAnchor').each(function(){
if($(this).is(":visible")){
var data_style = $(this).attr('data-style');
if(data_style!== undefined && data_style!== false){
$(this).attr('style',data_style).removeAttr("data-style");
}
}
});发布于 2012-02-23 17:15:40
有两件事发生了:
1)您应该使用javascript中的typeof函数检查它是否未定义,如下所示:
$('.bgAnchor').each(function(){
if($(this).is(":visible")){
var data_style = $(this).attr('data-style');
if(typeof data_style!== 'undefined' && data_style!== false){
var attr_image = $(this).attr("data-style");
alert(attr_image);
$(this).css('background', attr_image).removeAttr("data-style");
}
}
});(要很好地解释原因,请参见这个关于类型的回答
2)您试图使用$(this).css('background', attr_image)调用传递太多的“后台”样式。因此,您需要按以下方式更改数据样式属性:
<div class="bgAnchor" data-style="url('http://it.bing.com/az/hprichbg?p=rb%2fNewRiverGorgeBridge_ROW468427072.jpg') no-repeat"></div>如果要设置背景位置等,可以在css中为所有.bgAnchor元素设置背景位置,也可以为背景位置添加新的数据样式,但不能将背景位置和背景同时插入到后台css属性中。
https://stackoverflow.com/questions/9417626
复制相似问题