我正在尝试使用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>
答案 0 :(得分:0)
试一试:
<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>
答案 1 :(得分:0)
使用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>
答案 2 :(得分:0)
加载页面后立即执行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>
答案 3 :(得分:0)
如果您使用的是JQuery,可以使用this example。
$('document').ready(function() {
var div = document.getElementById('divChange');
div.style.backgroundColor = 'red';
});
&#13;
<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>
&#13;
您也可以使用this code
<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>
&#13;
答案 4 :(得分:0)
调用你的myDIV()方法onload事件。
<body onload="myDIV()">
your content goes here.
</body>
感谢。