javascript 有条件地改变 fontFamily
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13757011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
changing fontFamily conditionally
提问by BLOB
I wish to change the font-family of a paragraph continuously after every 1 second.. Here is my non-working code...
我希望每 1 秒后连续更改一个段落的字体系列.. 这是我的非工作代码......
<!DOCTYPE html>
<html>
<head>
<script src = "jquery.js"> </script>
<script>
$(document).ready(function() {
var idee = document.getElementById('p1');
changeFont();
});
function changeFont()
{
if(idee.style.fontFamily == 'times')
{
idee.style.fontFamily = 'courier';
}
else if(idee.style.fontFamily == 'courier')
{
idee.style.fontFamily = 'times';
}
setTimeout(changeFont, 1000);
}
</script>
</head>
<body>
<p id="p1">This is some text.</p>
</body>
</html>
So.. what am I doing wrong? How to change font conditionally?
所以..我做错了什么?如何有条件地更改字体?
回答by ameya rote
This code works fine..
这段代码工作正常..
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
function changeFont()
{
var idee = document.getElementById("p1").style.fontFamily;
if( idee == 'times')
{
document.getElementById("p1").style.fontFamily = 'courier';
}
else if(idee == 'courier')
{
document.getElementById("p1").style.fontFamily = 'times';
}
var int=setTimeout(function(){changeFont();},1000);
}
</script>
</head>
<body onload=" changeFont();">
<p id="p1" style="font-family: times;">This is some text.</p>
</body>
</html>
回答by Damon Smith
you have set var idee in the anonymous function inside the document ready but you're not passing it to changeFont, you're just calling changeFont and hoping that it's there on the global namespace.
您已经在文档内的匿名函数中设置了 var idee,但您没有将它传递给 changeFont,您只是调用 changeFont 并希望它在全局命名空间中。
try this first:
先试试这个:
<!DOCTYPE html>
<html>
<head>
<script src = "jquery.js"> </script>
<script>
$(document).ready(function() {
var idee = document.getElementById('p1');
changeFont(idee);
});
function changeFont(idee)
{
if(idee.style.fontFamily == 'times')
{
idee.style.fontFamily = 'courier';
}
else if(idee.style.fontFamily == 'courier')
{
idee.style.fontFamily = 'times';
}
setTimeout(function() {changeFont(idee)}, 1000);
}
</script>
</head>
<body>
<p id="p1">This is some text.</p>
</body>
</html>
回答by Osiris
idee
is being declared inside the anonymous function.
idee
是在匿名函数中声明的。
It will not be visible in changeFont.
它在 changeFont 中不可见。
<script>
var idee;
$(document).ready(function() {
idee = document.getElementById('p1');
changeFont();
});
AND
和
setTimeout('changeFont()',1000);
setTimeout('changeFont()',1000);