[英]My script is working in jsFiddle but not in my browser?
我是编程新手。 我正在学习HTML / CSS / Javascript atm。
我创建了一个简单的脚本,允许用户更改段落元素的字体大小。
我很累我的代码是jsFiddle并且可以正常工作,但是当我将其复制到HTML文档中并启动页面时。 HTML和CSS正常运行,但是问题是:JavaScript无法正常工作。 顺便说一句,我使用的是Chrome浏览器。
我的HTML文档有问题吗? 我很混乱!
这是工作中的jsFiddle: https ://jsfiddle.net/o60gtvh8/
我的HTML文件(下载链接/ Dropbox): https : //www.dropbox.com/s/tl0npr5omefntv4/Font%20size%20changer.rar? dl =0
HTML文件代码(以上下载链接中提供的HTML文件中代码的副本):
<!doctype html>
<html>
<head>
<style>
h1 {
color: blue;
font-size: 25px;
margin: 10px;
}
h2 {
color: blue;
font-size: 15px;
margin: 10px;
}
p {
margin: 10px;
}
a {
margin: 10px;
font-size: 15px;
text-decoration: none;
border: 1px solid grey;
background-color: cyan;
color: black;
padding: 3px;
}
</style>
<script>
function sizeChanger(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size10 = sizeChanger(10);
var size20 = sizeChanger(20);
var size30 = sizeChanger(30);
document.getElementById('size-10px').onclick = size10;
document.getElementById('size-20px').onclick = size20;
document.getElementById('size-30px').onclick = size30;
</script>
</head>
<body>
<h1>Tiger</h1>
<h2>(From Wikipedia, the free encyclopedia)</h2>
<p>The tiger (Panthera tigris) is the largest cat species, most recognizable for
their pattern of dark vertical stripes on reddish-orange fur with a lighter underside.
The species is classified in the genus Panthera with the lion, leopard, jaguar, and snow leopard.
</p>
<a href="#" id="size-10px">Font size 10</a>
<a href="#" id="size-20px">Font size 20</a>
<a href="#" id="size-30px">Font size 30</a>
</body>
</html>
将您的JavaScript移到结束body元素之前的页面末尾。 目前,您正在尝试访问尚不存在的元素。 jsFiddle之所以起作用,是因为默认情况下,它们将JavaScript代码包装在window.onload事件中。
h1 { color: blue; font-size: 25px; margin: 10px; } h2 { color: blue; font-size: 15px; margin: 10px; } p { margin: 10px; } a { margin: 10px; font-size: 15px; text-decoration: none; border: 1px solid grey; background-color: cyan; color: black; padding: 3px; }
<h1>Tiger</h1> <h2>(From Wikipedia, the free encyclopedia)</h2> <p>The tiger (Panthera tigris) is the largest cat species, most recognizable for their pattern of dark vertical stripes on reddish-orange fur with a lighter underside. The species is classified in the genus Panthera with the lion, leopard, jaguar, and snow leopard. </p> <a href="#" id="size-10px">Font size 10</a> <a href="#" id="size-20px">Font size 20</a> <a href="#" id="size-30px">Font size 30</a> <script> function sizeChanger(size) { return function() { document.body.style.fontSize = size + 'px'; }; } var size10 = sizeChanger(10); var size20 = sizeChanger(20); var size30 = sizeChanger(30); document.getElementById('size-10px').onclick = size10; document.getElementById('size-20px').onclick = size20; document.getElementById('size-30px').onclick = size30; </script>
因此,您的代码并没有真正的问题(尽管您应该避免使用诸如document.body.style.fontSize
类的传统DOM表示法)-您执行得太早了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.