[英]How can I change div HTML tag via button onclick event using javascript
[英]How can I change the color of the <div> using javascript without using onClick
我试图使用javascript更改<div>
的背景颜色,而不单击<div>
本身。 基本上,背景颜色会自行更改或在加载时更改。
这是我的HTML
代码:
<div id="divChange" onclick="myDIV()">
<span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport <?php echo "<strong><a href=\"view_latest_passport.php?id=$id\"> $passport</a> / Passport Expiration Date:</strong> $passport_expiration"; ?>
</div>
这是我的javascript
代码:
<script type="text/javascript">
function myDIV() {
document.getElementById("divChange").style.color="red";
}
</script>
试试吧 :
<html> <head></head> <body> <div id="divChange" onclick="myDIV()"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport <?php echo "<strong><a href=\\"view_latest_passport.php?id=$id\\"> $passport</a> / Passport Expiration Date:</strong> $passport_expiration"; ?> </div> <script> document.getElementById("divChange").style.backgroundColor="red"; </script> </body> </html>
使用window.onload
事件触发myDIV
方法
//call your myDIV on window.onload window.onload = function(){ myDIV(); } function myDIV() { //this triggers only the text color document.getElementById("divChange").style.color="white"; //use this to change background color document.getElementById("divChange").style.backgroundColor="red"; }
<div id="divChange">Sample DIV</div>
页面加载后立即执行JavaScript,请检查链接。
http://codepen.io/anil329/pen/kXvaPr
<html>
<head>
<title></title>
</head>
<body onload="myDiv()">
<div id="divChange">
<span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport
</div>
<script>
function myDiv() {
document.getElementById("divChange").style.color="red";
}
</script>
</body>
</html>
如果使用的是JQuery,则可以使用此示例 。
$('document').ready(function() { var div = document.getElementById('divChange'); div.style.backgroundColor = 'red'; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="divChange"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport <strong><a href="view_latest_passport.php?id=$id"> My Passport</a> / Passport Expiration Date:</strong> 23 JUN 2015 </div>
您也可以使用此代码
<body onload="myDiv()"> ... <div id="divChange"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport <strong> <a href="view_latest_passport.php?id=$id"> My Passport</a> Passport Expiration Date:</strong> 23 JUN 2015 </div> ... <script> function myDiv() { var div = document.getElementById( 'divChange' ); div.style.backgroundColor = 'red'; } </script> </body>
调用myDIV()方法onload事件。
<body onload="myDIV()">
your content goes here.
</body>
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.