Detecting the opening or closing of a details element

扶醉桌前 提交于 2019-12-09 02:49:00

问题


How can I detect when a details element is opened or closed in Javascript? Other than attaching a listener to the click function and checking if the open attribute is set or not.


回答1:


You can do something like this:

<details id="element">
   <p>Details</p>
</details>

<script>
   var isOpen = ($("#element").attr("open") == "open");

   alert ("Open = " + isOpen);
</script>



回答2:


You can use the toggle event:

var details = document.querySelector("details")

details.addEventListener("toggle", function() {
 details.firstChild.textContent = "done"
})
<!doctype html>
<details>
 <summary>toggle event</summary>
</details>



回答3:


In jQuery you can catch the event using .on('toggle') like this:

$('#detail-id').on('toggle', function() {
   //code
});


来源:https://stackoverflow.com/questions/7363117/detecting-the-opening-or-closing-of-a-details-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!