简体   繁体   English

使用Javascript切换点击背景色

[英]Toggling Background Color on Click with Javascript

I am working on a class project and need to be able to toggle the background color of a transparent png on click. 我正在上一个班级项目,需要能够在单击时切换透明png的背景颜色。 I have been working through a number of examples from the site, but I can't get it working. 我一直在研究该站点上的许多示例,但无法使其正常运行。 I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either. 我是Java的新手,也没有运气尝试插入jQuery代码。

Here is the targeted section: 这是目标部分:

        <div class="expenseIcon"><a href="#">
       <img src="images/mortgage.png"></a><br/>
       <p>Rent or Mortgage</p>
       </div>

On clicking the linked image, the goal is for the background on the image to change to green. 单击链接的图像时,目标是使图像上的背景变为绿色。 Clicking it again would change it back to the default, white. 再次单击它会将其更改回默认的白色。 Here's the CSS I'd like to toggle on/off with click. 这是我想通过点击打开/关闭的CSS。

      .colorToggle {
      background: #A6D785;
      }

I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work. 我曾尝试将class =“ iconLink”添加到href中,将class =“ iconBox”添加到图像中,而以下Javascript是从另一篇文章改编而来的,但是没有用。

var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
    var text = $(this).find(".iconBox");

    obj.var1 = text;
    //alert(obj.var1);
    //return false;

   $('.iconBox').removeClass('colorToggle');
   $(this).addClass('colorToggle')
});
});

Any advice would be greatly appreciated! 任何建议将不胜感激!

Let's break down what is happening with your current code when you click the link. 当您单击链接时,让我们分解一下当前代码所发生的情况。

var obj = {};
$(document).ready(function () {
    $(".iconLink").click(function () {
        var text = $(this).find(".iconBox");

        obj.var1 = text;

       $('.iconBox').removeClass('colorToggle');
       $(this).addClass('colorToggle')
    });
});
  1. JQuery finds all elements with the classname "iconBox". JQuery查找所有具有类名称“ iconBox”的元素。 In your case, this is the img element. 就您而言,这是img元素。 The reference to that element is then saved in "obj.var1". 然后,对该元素的引用将保存在“ obj.var1”中。 You do not end up doing anything with this reference, so these two lines can be removed. 您最终不会对该引用进行任何操作,因此可以删除这两行。

  2. All elements with the class "iconBox" have the class "colorToggle" removed. 具有“ iconBox”类的所有元素均已除去“ colorToggle”类。 Your img element didn't have this class on it, so nothing happens. 您的img元素上没有此类,因此什么也没发生。

  3. The class "colorToggle" is added to the anchor element. 将“ colorToggle”类添加到锚元素。 Yes! 是! Now the element wrapping the img has a background color. 现在,环绕img的元素具有背景色。

Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. 不幸的是,再次单击定位标记将无济于事,因为定位标记将已经具有“ colorToggle”类,而我们要做的就是尝试再次添加它。 Hmm. Let's try changing addClass to toggleClass. 让我们尝试将addClass更改为toggleClass。 Here's our new code: 这是我们的新代码:

$(document).ready(function () {
    $(".iconLink").click(function () {
        $(this).toggleClass('colorToggle');
    }
});

Also, note that because we're working with the anchor element, the p element won't be affected by this change. 另外,请注意,由于我们正在使用anchor元素,因此p元素不会受到此更改的影响。 If you want the entire div to change background colors, use this line instead: 如果要让整个div更改背景颜色,请改用此行:

$(".expenseIcon").toggleClass('colorToggle');

Using the given markup: 使用给定的标记:

  <!-- to toggle the bg-color onClick of anchor tag -->  
   <div class="expenseIcon">
      <a href="#">
         <img src="images/mortgage.png">
      </a>
      <br/>
      <p>Rent or Mortgage</p>
   </div>

since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method 由于该问题要求使用javascript,因此这里提供了一个使用内置js.style方法更新元素的背景色的选项

//get a handle on the link 
//only one element w/ className 'expenseIcon' 
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0]; 
//get a handle on the image 
var image = link.children[0];
//listen for click on link & call bgUpdate() 
link.addEventListener('click', bgUpdate, false);
function bgUpdate() { 
   if(image.style.backgroundColor === 'lightgoldenrodyellow'){
       image.style.backgroundColor = 'aliceblue';
   } else if (image.style.backgroundColor === 'aliceblue') {
        image.style.backgroundColor = 'lightgoldenrodyellow';
   }
   else console.log('image bgColor: ' + image.style.backgroundColor);
}

a similar example 一个类似的例子

css 的CSS

.expenseIcon{
      background: red;
}

.colorToggle {
      background: blue;
}

jquery jQuery的

$(".expenseIcon").click(function () {
   $('.expenseIcon').toggleClass('colorToggle');
});

By default, the div will have expenseIcon background. 默认情况下,div将具有consumerIcon背景。 ToggleClass will toggle the div class with colorToggle so will override the previous color. ToggleClass将使用colorToggle切换div类,因此将覆盖以前的颜色。 You don't need an hyperlink tag A to manage clicks, just put it on the DIV. 您不需要超链接标签A来管理点击,只需将其放在DIV上即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM