2015-08-28 74 views
0

所以我有一個按鈕,它的作用是切換並顯示視頻。如果再次點擊它將隱藏它,並繼續。它工作正常唯一的問題是,當你第一次點擊它,你必須點擊它兩次出於某種原因,我似乎無法弄清楚。JavaScript的切換使用按鈕

function togglevid() { 
 
    var e = document.getElementById("movie"); 
 
    if (e.style.display == 'none') e.style.display = 'block'; 
 
    else e.style.display = 'none'; 
 
    if (e.pause == false) e.pause() 
 
    else e.pause() 
 
}
#movie { 
 
    position:absolute; 
 
    top:158px; 
 
    left:470px; 
 
    display:none; 
 
    z-index:10 
 
}
<video controls="" height="400" id="movie" oncontextmenu="return false;" 
 
    width="960"> 
 
    <source src="" type="video/mp4"> 
 
    Your browser does not support HTML5 video.</video> 
 

 
<input id="mcodebtn" onclick="togglevid()" type="button" value= 
 
       "">

相信此錯誤的原因是事實,我有視頻設置爲顯示:無;默認。下面的代碼

回答

0

嘗試,style屬性應該設置爲display:none

的問題是,您試圖訪問style屬性,然後訪問display值。但是,第一次運行它時,video標記沒有任何style屬性集。

function togglevid() { 
 
    var s = document.getElementById("newcode"); 
 
    var e = document.getElementById("movie"); 
 
    if (e.style.display == 'none') e.style.display = 'block'; 
 
    else e.style.display = 'none'; 
 
    if (s.style.display == 'none') s.style.display = 'block'; 
 
    else s.style.display = 'none'; 
 
    if (e.pause == false) e.pause() 
 
    else e.pause() 
 
}
#movie { 
 
    position:absolute; 
 
    top:158px; 
 
    left:470px; 
 
    display:none; 
 
    z-index:10 
 
}
<video controls="" 
 
     height="400" 
 
     id="movie" 
 
     oncontextmenu="return false;" 
 
     width="960" 
 
     style="display:none;"><!-- Here we set a default value for style attr--> 
 
    <source src="" type="video/mp4"> 
 
    Your browser does not support HTML5 video.</video> 
 

 
<input id="mcodebtn" onclick="togglevid()" type="button" value= 
 
       "">

+0

嘿代window.getComputedStyle() @ leo.fcx它的工作。視頻標籤不是#video css風格嗎?我不明白爲什麼單獨的功能。 – L3SAN

0

試用e.style.display

function togglevid() { 
 
    var e = document.getElementById("movie"); 
 
    e.style.display = window.getComputedStyle(e, null) 
 
        .getPropertyValue("display") === "none" 
 
        ? "block" : "none"; 
 
}
#movie { 
 
    position: absolute; 
 
    top: 158px; 
 
    left: 470px; 
 
    display: none; 
 
    z-index: 10 
 
}
<video controls="" height="400" id="movie" oncontextmenu="return false;" width="960"> 
 
    <source src="" type="video/mp4"> 
 
    Your browser does not support HTML5 video.</video> 
 

 
<input id="mcodebtn" onclick="togglevid()" type="button" value="toggle">