[英]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.