Detecting the opening or closing of a details elem

2020-03-10 04:31发布

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.

3条回答
不美不萌又怎样
2楼-- · 2020-03-10 04:48

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

$('#detail-id').on('toggle', function() {
   //code
});
查看更多
姐就是有狂的资本
3楼-- · 2020-03-10 05:04

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>

查看更多
\"骚年 ilove
4楼-- · 2020-03-10 05:07

You can do something like this:

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

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

   alert ("Open = " + isOpen);
</script>
查看更多
登录 后发表回答