通过备用点击切换2种颜色之间div的背景颜色

时间:2017-07-22 22:02:47

标签: javascript html css

我有一个ID为ID" box"。其初始背景颜色设置为#ff7700。我想创建一个函数" function1()"做以下事情:

  • 首次点击:将背景颜色更改为#ff0077
  • 第二次点击:将背景颜色更改回#ff7700
  • 第三次点击:将背景颜色更改为#ff0077
  • 第四次点击:将背景颜色更改回#ff7700,依此类推。

代码:

<style>
    #box{
    background-color: #ff7700;
    cursor: pointer;
}    
</style>

<div id="box" onClick="function1()" > Inner HTML</div>

我尝试编写一个函数,但它无效。

<script>
    function function1(){
        var check = document.getElementById("box").style;
        check2=check.backgroundColor;
        if (check2 != "#ff0077"){
            check2="#ff7700";
            } else {
               check2="#ff0077";
            }
       }
</script>

请告知任何其他方法。我想坚持核心JS而不是使用Jquery。

6 个答案:

答案 0 :(得分:3)

最好使用布尔值作为切换:

&#13;
&#13;
public static String encodeTurkishCharactersInUrl(String url) {
        String[] list = new String[]{"ü", "ç", "ı", "ö", "ğ", "ş", "", "Ü", "Ç", "İ", "Ö", "Ğ", "Ş"};
        for (int i = 0; i < list.length; i++) {
            try {
                url = url.replace(list[i], URLEncoder.encode(list[i], "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        url = url.replaceAll(" ", "%20");

        return url;
    }
&#13;
var div = document.getElementById("box"),
    toggle = false;
    
div.onclick = function() {
  toggle = !toggle;                                     // invert toggle
  div.style.background = toggle? "#ff0077": "#ff7700";  // change background color depending on the value of toggle
}

div.style.background = "#ff7700";                       // give the div an initial background
&#13;
&#13;
&#13;

答案 1 :(得分:2)

我使用jQuery做了一个简单的例子。我希望我有所帮助。

基本上我得到了一个带有类&#34; .myDiv&#34;的元素。并向其添加单击事件。始终点击元素&#34; toggleClass()&#34;方法切换班级。

&#13;
&#13;
$(document).ready(function(){
  $(".myDiv").bind("click", function(){
    $(this).toggleClass("myClass");
  });
});
&#13;
.myDiv{
  padding: 1em;
  font-family: "Helvetica", sans-serif;
  line-height: 1.5em;
  background: #cccccc;
}

.myClass{
  background: red;
  color: white;
}
&#13;
<div class="myDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda facere, cumque aliquam quis aut, velit quidem, repellendus quo maiores saepe unde sed reprehenderit laborum? Eum laborum possimus quidem, ea non.</p>
</div>

<!--jQuery Libary-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

  1. 从css选择器background-color: #ff7700;
  2. 中删除#box
  3. 创建2个css类,说AB并相应地添加背景颜色
  4. 获取dom元素var domEl = document.getElementById("box"); 之后,如果domEl.className==="A",则为其分配"B", 否则请指定"A"

答案 3 :(得分:1)

.style属性不返回十六进制颜色代码。您可以使用window.getComputedStyle()获取计算出的CSS属性,将颜色设置为rgb()

<style>
  #box {
    background-color: #ff7700;
    cursor: pointer;
  }
</style>
<script>
  function function1() {
    if ( window.getComputedStyle(box).backgroundColor === "rgb(255, 119, 0)") {
      box.style.backgroundColor = "rgb(255, 0, 119)";
    } else {
      box.style.backgroundColor = "rgb(255, 119, 0)";
    }
  }
  onload = function() {
    const box = document.getElementById("box");
  }
</script>
<div id="box" onClick="function1()"> Inner HTML</div>

另见Is it possible to change the background color and back to the original in plain javascript every time i click a button?

答案 4 :(得分:1)

您将使用getComputedStyle()获取元素的颜色,这会将您的颜色恢复为rgb()格式。如果您需要将rgb()更改为hex,请在this post上了解详情。

以下是

的例子

&#13;
&#13;
function function1(){
    var check = document.getElementById("box");
    var color = window.getComputedStyle(check, null).getPropertyValue('background-color');  
    if (color != "rgb(255, 119, 0)"){
      check.style.backgroundColor = "rgb(255, 119, 0)";
    } else {
      check.style.backgroundColor = "rgb(255, 255, 255)";
    }
}
&#13;
#box{
    background-color: #ff7700;
    cursor: pointer;
}    
&#13;
<div id="box" onclick="function1()">Inner HTML</div>
&#13;
&#13;
&#13;

答案 5 :(得分:1)

使用内联js代码我建议传递 this 变量:current元素。这样您就不需要选择元素了。

使用window.getComputedStyle并将值转换为十六进制值,代码为:

function function1(ele) {
    var background = window.getComputedStyle(ele).backgroundColor;
    var hexColor = rgb2hex(background);
    if (hexColor != "#ff0077") {
        ele.style.backgroundColor = "#ff0077";
    } else {
        ele.style.backgroundColor = "#ff7700";
    }
}



function rgb2hex(rgb) {
    rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
    return (rgb && rgb.length === 4) ? "#" +
    ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
}
#box {
    background-color: #ff7700;
    cursor: pointer;
}
<div id="box" onClick="function1(this)"> Inner HTML</div>