onfocus olayı

Tanım ve Kullanım

onfocus olayı bir element odaklandığında gerçekleşir.

onfocus olayı en sık <input>、<select> ve <a> ile birlikte kullanılır.

İpucu: onfocus olayı ile onblur olayıTam tersi.

İpucu: onfocus olayı benzerdir onfocusin olayı。Ana fark, onfocus olayının taşması olmayacağıdır. Bu nedenle, bir elementin veya alt elementlerinin odaklandığını belirlemek istiyorsanız, onfocusin olayını kullanabilirsiniz. Ancak, onfocus olayını kullanarak addEventListener() yönteminın useCapture Bu nedeni gerçekleştirmek için parametreleri kullanın.

Örnek

Örnek 1

Girdi alanı odaklandığında JavaScript çalıştırılır:

<input type="text" onfocus="myFunction()">

Kendi kendine deney

Sayfa altında daha fazla TIY örneği bulunmaktadır.

Gramer

HTML'de:

<element onfocus="myScript">

Kendi kendine deney

JavaScript'te:

nesne.onfocus = function() {myScript};

Kendi kendine deney

JavaScript'te, addEventListener() yöntemini kullanarak:

nesne.addEventListener("focus", myScript);

Kendi kendine deney

Yorum:Internet Explorer 8 veya daha eski sürümler desteklenmez addEventListener() yöntemi

技术细节

冒泡: 不支持
可取消: 不支持
事件类型: FocusEvent
支持的 HTML 标签: 所有 HTML 元素,除了:<base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> 以及 <title>
DOM 版本: Level 2 Events

浏览器支持

事件 Chrome IE Firefox Safari Opera
onfocus 支持 支持 支持 支持 支持

更多实例

例子 2

将 "onfocus" 与 "onblur" 事件一起使用:

<input type="text" onfocus="focusFunction()" onblur="blurFunction()">

Kendi kendine deney

例子 3

清空获得焦点的输入字段:

<!-- 当输入字段获得焦点时,将其当前值替换为空字符串 -->
<input type="text" onfocus="this.value=''" value="Blabla">

Kendi kendine deney

例子 4

事件委托:将 addEventListener() 的 useCapture 参数设置为 true:

<form id="myForm">
  <input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);
function myFocusFunction() {
  document.getElementById("myInput").style.backgroundColor = "yellow"; 
}
function myBlurFunction() {
  document.getElementById("myInput").style.backgroundColor = ""; 
}
</script>

Kendi kendine deney

例子 5

事件委托:使用 focusin 事件(Firefox 不支持):

<form id="myForm">
  <input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focusin", myFocusFunction);
x.addEventListener("focusout", myBlurFunction);
function myFocusFunction() {
  document.getElementById("myInput").style.backgroundColor = "yellow"; 
}
function myBlurFunction() {
  document.getElementById("myInput").style.backgroundColor = ""; 
}
</script>

Kendi kendine deney