我正在尝试使用Javascript进行简单的淡出效果。
当我在我的文本编辑器+谷歌浏览器中尝试它时,它无法正常工作,因此我将其复制到JSFiddle中并且有效!
但是,我无法弄清楚JSFiddle中哪些内容在原始副本中不正确。
我将在Notepad ++中发布代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<html>
<head>
<title>My Site</title>
<link rel="stylesheet" type="text/css" href="style2.css">
</style>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-08000000-1', 'mysite.com');
ga('send', 'pageview');
</script>
<script type="text/javascript" src="js/jquery_1.4.2.js"></script>
<script type="text/javascript" src="js/flashing_logos.js"></script>
</head>
<body>
<div id="background_logo">
<img src="http://drivesmartbc.ca/sites/default/files/images/smiley%20face.thumbnail.jpg">
</div>
<div id="logo">
<img src="https://lh4.googleusercontent.com/-b86bjfIcDMk/TXpUmwBK_FI/AAAAAAAAARY/ws-ypr2P39I/s200/9+smiley+face.jpg">
</div>
<div id="signup">
<p id="instruction"> Get on board! </br> Enter your email to receive updates:</p>
<script type="text/javascript" src="js/form-validation.js"></script>
<form id="emailForm" action='#' method="post">
<input name="email" id="email" type="text" />
<input type="button" value="Submit" name="submit" id="submit" />
</form>
<p id="success" class="success">Thanks - we'll keep in touch!</p>
<p id="error" class="warning">There was an error</p>
</div>
</body>
</html>
我的Javascript看起来像这样:
function fade(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
fade(document.getElementById('background_logo'));
答案 0 :(得分:2)
您正在document.getElementById('background_logo')
中的脚本调用head
,而您之后调用的函数则没有这样做。
在解析主体之前,该元素不存在。
将脚本移动到<div id="background_logo">
结束之后(例如,在</body>
之前)或将其包装在函数中可以在DOM ready或Load上调用它(这是JSFiddle默认执行的操作)
另见Why does jQuery or a DOM method such as getElementById not find the element?。