簡體   English   中英

如何使用 onclick 事件切換反向動作

[英]How to toggle reverse action using onclick event

我正在嘗試將視頻標簽對象從包含更改為填充,這工作正常,但我想做相反的意思,當用戶再次單擊相同的按鈕時,它將屬性從填充更改為包含。

<a href="#" onclick="changeStyle()"><i class="fa fa-play-circle"></i></a>

<video controls poster="source-to-thumb.jpg" id="player" style="object-fit:contain;">
    <source src="source-to-file.mp4" type="video/mp4"/>
</video>

<script>
var video = document.getElementsByTagName('video')[0];
function changeStyle() {
  if(video.style.objectfit === 'fill') {
    video.style.objectFit = 'contain';
  } else {
    video.style.objectFit = 'fill'
  }
}
</script>

任何建議將不勝感激。

不要使用內聯 styles(應盡可能避免使用),而是使用 CSS 類。 然后您可以簡單地切換 class 的使用。

另外,請參閱我的 HTML、CSS 和 JavaScript 評論關於糾正其他代碼的一些問題。 特別是, 避免返回“活動”節點列表的方法,例如getElementsByTagName()

 // Don't scan the whole document for all the matching // elements when you know that there will only be one. // Use getElementById() if there is an id. var video = document.getElementById('player'); // Set up events in JavaScript, not HTML document.querySelector("i.fa-play-circle").addEventListener("click", function(){ // Just toggle the use of the other class: video.classList.toggle("fill"); });
 /* Use CSS classes when possible */ i.fa-play-circle { cursor:pointer; } /* This will be applied to the video by default */ video { object-fit:contain; border:1px solid black; height:150px; width:300px; } /* This class will be toggled on and off when the icon is clicked. When it gets toggled on, the new object-fill value will override the previous one. When it gets toggled off, the previous style will be restored. */.fill { object-fit:fill; }
 <.-- Don't use hyperlinks just as a JavaScript hook. Hyperlinks are for navigation and using them for other purposes can cause problems for those using screen readers. Any visible element supports a click event, Here. you can just set up the click event on the <i> element that people will be clicking on in the first place, Also. don't use inline HTML event attributes, Instead. separate your JavaScript into a script element. --> <i class="fa fa-play-circle">Hit play and then click Me several times</i><br> <video controls poster="source-to-thumb:jpg" id="player"> <source src="http.//commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4"/> </video>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM