首页 > 解决方案 > 在循环中使用 .getAttribute 添加样式

问题描述

第一次在这里发帖。希望有人能帮忙?!

我正在尝试将样式添加到我通过在 HTML 中添加数据属性然后使用 JS 在轮播中循环遍历每个图像来创建的视差轮播中。我能够将“数据背景”添加到内联样式中,但“数据位置”不是。

预期产出

<div class="parallax-container parallax-scale" 
data-background="//localhost:3000/wp-content/uploads/2020/03/animage.jpg" 
data-position="50% 50%" data-swiper-parallax="1130.25" 
style="transform: translate3d(0px, 0px, 0px); background-image: url("//localhost:3000/wp-content/uploads/2020/03/animage.jpg"); background-position: 50% 50%;">

var list = document.getElementsByClassName('parallax-container');

for (var i = 0; i < list.length; i++) {
  var src = list[i].getAttribute('data-background');
  list[i].style.backgroundImage = "url('" + src + "')";
  var pos = list[i].getAttribute('data-position');
  list[i].style.backgroundPosition = pos;
  console.log(list[i])
}
<div class="parallax-container parallax-scale" data-background="//localhost:3000/wp-content/uploads/2020/03/animage.jpg" data-position="50% 50%">

标签: javascriptloopsgetattribute

解决方案


推荐阅读