【问题标题】:jQuery - Change CSS of one element from many with same class identificationjQuery - 从具有相同类标识的多个元素中更改一个元素的 CSS
【发布时间】:2014-11-04 23:45:35
【问题描述】:

我正在处理一个简单的 jQuery 脚本,该脚本在单击时更改元素的背景颜色。

这是我的代码:

<script src="//code.jquery.com/jquery-1.10.2.js"></script>

<div class="radio">Text1</div>
<div class="radio">Text2</div>
<div class="radio">Text3</div>
<div class="radio">Text4</div>

我希望发生以下情况:

我点击“Text1”,这个 div 正在将他的背景颜色更改为红色并保持红色。

我点击“Text2”,“Text1”的背景颜色变回白色,然后“Text2”的背景颜色变回并保持红色。

希望我给你一个好的描述。

你能帮我做吗?

提前致谢!

【问题讨论】:

    标签: jquery html css


    【解决方案1】:

    $('.radio').click(function(){
      $('.red').removeClass('red');
      $(this).addClass('red');
    });
    .red{
    background-color: red; 
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <div class="radio">Text1</div>
    <div class="radio">Text2</div>
    <div class="radio">Text3</div>
    <div class="radio">Text4</div>

    【讨论】:

      【解决方案2】:

      这是一种使用纯 CSS 的方法:

      input {
        display: none;
      }
      label {
        display: block;
      }
      input:checked + label {
        background-color: red;
      }
      <input id="text1" type="radio" name="g1">
      <label for="text1">Text1</label>
      <input id="text2" type="radio" name="g1">
      <label for="text2">Text2</label>
      <input id="text3" type="radio" name="g1">
      <label for="text3">Text3</label>
      <input id="text4" type="radio" name="g1">
      <label for="text4">Text4</label>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多