簡體   English   中英

JQuery 防止元素獲得焦點?

[英]JQuery to prevent an element from getting focus?

如何防止輸入元素(文本、文本區域、選擇、單選按鈕、復選框)獲得焦點? 我基本上想讓它們禁用而不更改 disabled 或 readonly 屬性但否認它們的焦點。 有沒有一種巧妙的方法可以使用某些搜索條件掃描 DOM 並將其應用於搜索結果? 假設我想找到所有沒有用某個 css 類標記的輸入並使它們不可選擇!

將應該被允許聚焦的元素賦予focus類。 然后使用使元素不聚焦的focus事件處理程序。

 $(document).on("focus", ":input:not(.focus)", function() { $(this).blur(); console.log("Focus blocked"); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox"> No focus<br> <input type="checkbox" class="focus"> Focus

這使用事件委托,因此您可以動態添加和刪除focus類。

我不確定我是否明白你的意思,但你能運行這個嗎:

 $('#disabler').change(function() { resetFields(); var this_value = $(this).val(); if(this_value != 'none'){ $('.'+this_value).attr('disabled', true); } }); $('.disabler').click(function(){ resetFields(); var this_value = $(this).attr('id'); $('.'+this_value).attr('disabled', true); }); $('#reset').click(function(){ resetFields(); }); function resetFields() { $('.first, .second').removeAttr('disabled'); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="first" value="A"><br/> <select class="first"><option value="1">A</option></select><br/> <textarea class="first" col="2" row="10">A</textarea><br/> <br/><br/> <input class="second" value="B"><br/> <select class="second"><option value="1">B</option></select><br/> <textarea class="second" col="2" row="10">B</textarea><br/> <br/><br/> <select id="disabler"> <option value="none">-select-</option> <option value="first">Disable first</option> <option value="second">Disable second</option> </select><br/> <button id="first" class="disabler">Disable first only</button><br/> <button id="second" class="disabler">Disable second only</button><br/> <button id="reset">Reset</button>

暫無
暫無

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

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