[英]Jquery to check if inside element
如果用戶在元素中單擊,我試圖將一個類添加到元素中。
所有通常的規則都適用-“內部”表示它可以在孩子,孫子等內部。
如果在內部,則需要添加一個類-如果在外部,則應刪除該類。
我拼湊了這個示例,該示例可以正常工作,但是作為一個非JavaScript的人,我希望能收到一些有關它是否是一種合理方法的反饋,如果可以改進的話-通過改進,我引用了jquery / javascript性能。
任何建議表示贊賞。
$("body").click(function (e) {
$fs = $(e.target).closest("fieldset.expand");
if ($fs.length) {
$fs.addClass("focus");
}
else {
$("fieldset.expand").removeClass("focus");
}
});
<body>
<fieldset class="expand">
<input type="text" />
<input type="text" />
<input type="text" />
</fieldset>
</body>
使你的fieldset
可聚焦(但不tabbable),使用tabindex
屬性具有負值。 然后使用focusin focusout
事件設置邏輯:
$('fieldset.expand').on('focusin focusout', function() { $(this).toggleClass('focus', $(this).find('*').addBack().is(':focus')); });
fieldset.focus { outline: 0; background: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <fieldset tabindex="-1" class="expand"> <input type="text" /> <input type="text" /> <input type="text" /> </fieldset>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.