簡體   English   中英

我該如何改變顏色 <div> 使用JavaScript而不使用onClick

[英]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>&nbsp;&nbsp;Passport <?php echo "<strong><a href=\"view_latest_passport.php?id=$id\"> $passport</a> /&nbsp; 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>&nbsp;&nbsp;Passport <?php echo "<strong><a href=\\"view_latest_passport.php?id=$id\\"> $passport</a> /&nbsp; 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>&nbsp;&nbsp;Passport 
    </div>

    <script>
    function myDiv() {
      document.getElementById("divChange").style.color="red";
    }
    </script>
  </body>
</html>

選擇#1(使用JQuery)

如果使用的是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>&nbsp;&nbsp;Passport <strong><a href="view_latest_passport.php?id=$id"> My Passport</a> /&nbsp; Passport Expiration Date:</strong> 23 JUN 2015 </div> 

替代方法2(不使用JQuery)

您也可以使用此代碼

 <body onload="myDiv()"> ... <div id="divChange"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span>&nbsp;&nbsp;Passport <strong> <a href="view_latest_passport.php?id=$id"> My Passport</a> &nbsp; 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM