[英]Changing css using javascript works inline but not from header
I have a div area that I want to change the css after the page loads. 我有一个div区域,我想在页面加载后更改CSS。 My HTML looks like the following
我的HTML如下所示
<div class='myArea'>
</div>
<script type="text/javascript">
$('.myArea').css('background-color',"red");
</script>
And it works. 而且有效。 But if I move this to an external js file and reference the js file from the header, this doesn't work.
但是,如果我将其移至外部js文件并从标头引用js文件,则此操作将无效。 The following is the js code in the external file -
以下是外部文件中的js代码-
function init(){
$('.myArea').css('background-color',"blue");
}
window.addEventListener('load', init, false);
What might be the reason behind this 这可能是什么原因
You only have to put the code inside jQuery document ready function, $() is a shortcut to that function: 您只需要将代码放入jQuery文档ready函数中,$()是该函数的快捷方式:
$(function(){
$('.myArea').css('background-color',"red");
});
Try this instead?: 试试这个吗?:
window.onload = function() {
$('.myArea').css('background-color',"red");
}
Or, if you're already using jQuery, you could use their document ready(): http://api.jquery.com/ready/ 或者,如果您已经在使用jQuery,则可以使用其文档ready(): http : //api.jquery.com/ready/
$( document ).ready(function() {
$('.myArea').css('background-color',"red");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.