Blur(unfocus) an element when other element is clicked

删除回忆录丶 提交于 2021-01-29 20:10:42

问题


document.addEventListener("click", function (e) {
var filter = document.getElementById('filter');
  if (e.target !== filter[0]) {
    filter.blur();
  }
});

My attempt ^^

jQuery Code:

$(document).on('click', function(e) { 
  if (e.target !== $('#filter')[0]) 
  $('#filter').blur();
});

When any element except #filter is clicked I would like to blur (unfocus) #filter


回答1:


You don't need to dereference the result of getElementById with the [0] - the result is already a single element.

The [0] is only necessary in jQuery because jQuery results are always pseudo-arrays even if there's only one matching element.

Given this function is being called for every single click on the page, consider moving the definition of filter outside of the function so that you don't have to re-evaluate it for every click (assuming that the element is static).



来源:https://stackoverflow.com/questions/24300118/blurunfocus-an-element-when-other-element-is-clicked

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