Html Javascript 更改 DIV 背景颜色 onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17026653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:17:13  来源:igfitidea点击:

Javascript Change DIV background color onclick

javascripthtmlcssbackground-color

提问by user1190466

I'm trying to change the colour of a div after a form has been submitted. The div on the new page should be in the colour selected.

我正在尝试在提交表单后更改 div 的颜色。新页面上的 div 应采用所选颜色。

JS

JS

 function change(col) {   
     col.style.backgroundColor = '<?php echo $colour ?>';    
 }

HTML

HTML

<form action="" method="post">
    <input type='search' name='keywords' value='' style="width:100%;">
<a href='#col'>
<input type=submit  value='Submit' name='doSearch' style="visibility: hidden;" onclick="change(this.href)" />
 </a>

</form>
<div id="col" onclick="location.href='index2.php';">
    <br/>
    <?php echo $message ?>
</div>

采纳答案by Alessandro Gabrielli

<? $message="dd"; ?>
<script>
function change(col) {
document.getElementById('col').style.backgroundColor=col;
}
 </script>

<form action="" method="post">
<input type='search' name='keywords' value='' style="width:100%;">

<a href='#col'>
<input type=submit  value='Submit' name='doSearch' style="visibility: hidden;" onclick="enter(this.href)" />
 </a>
 </form>


<div style="width:50px; height:50px;" id="col" onclick="location.href='index2.php';" >

 <br/>
<?php echo $message ?>

</div>
<? if(isset($_POST['keywords'])){ ?>
<script>
 change('<?=$_POST['keywords']?>');
</script>
<? } ?>

test it, it works by inserting the color on the keywords input

测试一下,它的工作原理是在关键字输入上插入颜色

回答by BeNdErR

have a look here: http://jsfiddle.net/TeFYV/

看看这里:http: //jsfiddle.net/TeFYV/

code

代码

var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"]

function changeColor() {
    //you can as well pass col reference as you do in your code
    var col = document.getElementById("changecolor");
    col.style.backgroundColor = colors[Math.floor((Math.random()*8)+1)];
}

Adapt to your needs, hope it helps

适应您的需求,希望对您有所帮助

回答by Stefano L

You could do this easily with jQuery:

您可以使用 jQuery 轻松完成此操作:

$("#yourID").click(function(){

  $(this).css("background-color","yellow");

  });

回答by Johann Strydom

Easiest way would be to pass the color as a parameter between the two pages and then use jQuery on the second page to set the color with the one you got from that parameter.

最简单的方法是将颜色作为参数在两个页面之间传递,然后在第二页上使用 jQuery 用您从该参数获得的颜色设置颜色。