有条件地改变fontFamily

时间:2012-12-07 04:39:16

标签: javascript css

我希望每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>

那么......我做错了什么?如何有条件地改变字体?

3 个答案:

答案 0 :(得分:5)

此代码工作正常..

<!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>

答案 1 :(得分:2)

你已经在文档中的匿名函数中设置了var idee,但你没有将它传递给changeFont,你只是调用changeFont并希望它在全局命名空间中存在。

先试试这个:

<!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>

答案 2 :(得分:-1)

idee正在匿名函数中声明。

在changeFont中不可见。

<script>
var idee;
$(document).ready(function() {

    idee = document.getElementById('p1');   

    changeFont();
}); 

setTimeout('changeFont()',1000);