使用未知CSS时,使用JavaScript更新内容

时间:2015-12-29 18:54:42

标签: javascript html css

我正在构建一个网页,我在使用Javascript时遇到了麻烦。我想在固定位置创建一个按钮来完成游戏的全屏。此按钮使用材质设计css,javascript和图标库:http://www.getmdl.io/components/index.html#buttons-section

问题在于全屏有两个不同的图标。一个退出,一个退出。

两个代码都应该是这样的

进入全屏模式

<button class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored">
  <i class="material-icons">fullscreen</i>
</button>

退出全屏模式

<button class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored">
  <i class="material-icons">fullscreen exit</i>
</button>

我正在尝试编写一个javasccript代码,用于在按钮单击时自动更改图标。

我所做的HTML代码是

    <div>    
   <button id="buttonFullScreen" class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored" onclick="doFullScreen()">
  <i id="iconFullScreen" class="material-icons"></i>
            <script>document.getElementById("iconFullScreen").innerHTML = "fullscreen";</script><!--This is to try to put fullscreen as default but it is not working-->
</button>
        </div>

我所做的JS代码是

 var fullscreen = false;

function doFullScreen() {

    if(fullscreen){

        fullscreen = !fullscreen;

    }else{
    //If it is not on fullscreen, we put there.
        window.scrollTo(0,0);
        fullscreen = !fullscreen;
    }
    if(fullscreen) document.getElementById("iconFullScreen").innerHTML = "fullscreen";
    else document.getElementById("iconFullScreen").innerHTML = "fullscreen exit";


}


window.onscroll = function () { 
   if(fullscreen) window.scrollTo(0, 0); 
    else return;
}

我无法更新整个页面,因为它是一款游戏。 我需要在现场更改图标。 页面加载完成后,我无法放置默认图标。 [说明:默认图标应该是“全屏”,但我不知道放在哪里]

问题是:当我点击按钮时如何更改图标?如何将图标设为默认图标。

〜非常感谢

1 个答案:

答案 0 :(得分:0)

您的默认值可以在HTML中设置或动态

<body onload='assignDefault()'>

    ... some code ...
    <div>    
        <button id="buttonFullScreen" class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored" onclick="doFullScreen()">
            <i id="iconFullScreen" class="material-icons">fullscreen</i> <!-- default value loads with html -->
        </button>
    </div>
</body>

你的JS用于分配默认值应该是这样的:

assignDefault = function(){
    document.getElementById("iconFullScreen").innerHTML = "fullscreen";
}

至于分配全屏,修复和编辑:

var fullscreen = false;

function doFullScreen() {

    if(fullscreen){
        fullscreen = false;
        document.getElementById("iconFullScreen").innerHTML = "fullscreen";
    } else {
        window.scrollTo(0,0);
        fullscreen = true;
        document.getElementById("iconFullScreen").innerHTML = "fullscreen exit";
    }
}