如何替换 Background-attachment:fixed on Mobile?

How to replace Background-attachment:fixed on Mobile?

我的网站上有多个部分提供“视差”风格的背景效果,这在许多移动平台上被禁用。

我想使用一些 jQuery 或 javascript 来替换样式 "background-attachment:fixed" 的所有实例以用于 "background-attachment: scroll"

我不喜欢手动更新每个位置(这是一个巨大的项目),我很高兴在移动设备上失去视差效果并退回到 background-size: cover

没有发布任何代码,因为我不确定从哪里开始。

你可以做类似

if (!window.matchMedia("(min-width: 800px)").matches) {  
    var items = document.getElementsByClassName("some_class");
    for (var i = 0; i < items.length; ++i) {
      var item = items[i];
      if (item.style.backgroundAttachment == "fixed") {
          item.style.backgroundAttachment = "scroll";
      }
    }
}

我没有测试过这个,我怀疑它不会解决你的问题,因为你没有一个 class 名字。你也可以 运行 它在所有 div 或其他东西上。

如果所有这些元素共享相同的 class 名称,比如说 bg,那么它可能是这样的:

JS: JS Fiddle 1 - 我忘了 for-loop 这里是纯 javascript

if(isMobile) {
    var backgrounds = document.getElementsByClassName('bg');

    for(var i in backgrounds){
        backgrounds[i].style.backgroundAttachment = 'scroll';
    }
}

jQuery: JS Fiddle 2

if(isMobile) {
    $('.bg').css({'background-attachment':'scroll'});
}
  • 请注意,isMobile 可能是您触发的变量 true 如果它是移动的,则取决于 userAgent 或 window 宽度

下面的片段

//find all elements
var elements=document.body.querySelectorAll('*');
//loop through all elements
for(var i=0;i<elements.length;++i){
  //find the inline or css style for each element
element_style=window.getComputedStyle(elements[i],null)||elements[i].currentStyle;
//if style matches fixed change style
  if(element_style.backgroundAttachment=='fixed'){
console.log(element_style.backgroundAttachment)
elements[i].style.backgroundAttachment='scroll';
    //alert box that show style has been changed
alert('this div background is now '+ element_style.backgroundAttachment)
}

}
div{
  background-image:url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQARVdhCSrk0o1t6uon-TqIJYit7b6unGWMn_zJu2Tg0LkoEi4Kpg');
  background-repeat: no-repeat;
  background-attachment:fixed;
  background-size:50px;
  border:solid;
  width:500px;
  height:100px;
  overflow:scroll;

}
<div>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
</div>

<div>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
</div>
<div>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
</div>