使用JS更改多个CSS类

时间:2017-10-07 10:29:34

标签: javascript jquery html css html5

我需要使用JS

更改5个具有相同名称的类和另一个名称

var left = document.getElementById("right").className = "left";
.right {
  float: right;
}

.left {
  float: left;
}
<button onclick="changeLeft()">Sinistra</button>
<div class="newsright">
  <img src="images/angular.png" alt="HTML" id="right" class="right">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用简单的jQuery:

function changeLeft() {
  $('.right').each(function() {
    $(this).removeClass('right');
    $(this).addClass('left');
  });
}
.newsright {
clear:both;
margin-bottom:5px;
}
.right {
  float: right;
}

.left {
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button onclick="changeLeft()">Sinistra</button>
<div class="newsright">
  <img src="https://lorempixel.com/100/50/" alt="HTML" class="right">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="newsright">
  <img src="https://lorempixel.com/60/40/" alt="HTML" class="right">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="newsright">
  <img src="https://lorempixel.com/50/50/" alt="HTML" class="right">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

你也可以让按钮在这两个类之间切换:

function switchClass() {
  $('.right,.left').each(function() {
    $(this).toggleClass('right left');
  });
}
.newsright {
clear:both;
margin-bottom:5px;
}
.right {
  float: right;
}

.left {
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button onclick="switchClass()">Sinistra</button>
<div class="newsright">
  <img src="https://lorempixel.com/100/50/" alt="HTML" class="right">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="newsright">
  <img src="https://lorempixel.com/60/40/" alt="HTML" class="right">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="newsright">
  <img src="https://lorempixel.com/50/50/" alt="HTML" class="right">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

答案 1 :(得分:-1)

您是否正在搜索:fiddle example

<script>
   function changeLeft () {
      var left = document.getElementById("right").className = "left";
   }
</script>

只需单击changeLeft函数,具有此类的元素就会更改为右侧: