css有类似有失去焦点设置样式的功能吗

html-css08

css有类似有失去焦点设置样式的功能吗,第1张

css2有获得焦点的选择器:

input:focus {...} //当input元素获得焦点时就会套用这个样式

也就是说当input元素失去焦点就会恢复为原来的样式。因此只需给同一类元素设置默认样式和获得焦点时的样式即可实现你的目的。

我这个回答评论里的 无名duter 朋友告知我说 “可以给div或者span元素添加属性tabindex”。姑且测试一下,是支持的,感谢无名duter !只能怪自己学艺不精。

那么简陋的代码如下:

<!doctype html>

<html>

<head>

    <meta name="author" content="青青水豌豆 "/>

    <title>当红色div失去焦点时隐藏</title>

</head>

<body>

    <script>

        //创建红色DIV方块

        red = document.createElement('div')

        red.setAttribute('id','red')

        red.setAttribute('tabindex','1')

        red.style.cssText = "width:100pxheight:100pxbackground-color:red"

        document.body.appendChild(red)        

        

        //创建黄色div方块 

        yellow = document.createElement('div')

        yellow.setAttribute('id','yellow')

        yellow.setAttribute('tabindex','2')

        yellow.style.cssText = "width:100pxheight:100pxbackground-color:yellow"

        document.body.appendChild(yellow)

        

        //当红色方块失去焦点时隐藏

        let redHide = document.getElementById('red')

        redHide.onblur = () =>  redHide.style.display = 'none'

    </script>

</body>

</html>

说明一下:以上代码用文本文档保存后,修改扩展名.html,然后再用chrome或者firefox或者最新版的微软Edge浏览器打开,IE浏览器不支持。双核浏览器请使用极速模式,兼容模式也是调用的IE也不支持。

-

-

-

--------------------------------------------------------------

以下是以前回答的。不做修改。

你好,DOM中的元素DIV不支持失去焦点事件onblur。

支持失去焦点的元素有button, checkbox, fileUpload, layer, frame, password,

radio, reset, submit, text, textarea, window。没有包括div

你可以让某个事件发生的时候尝试让这个div隐藏,比如

<div id="test">你需要为这个盒子设置宽高和颜色</div>

<button>btnnn</button>

<script>

var test = document.getElementById('test')

var btn  = document.getElementsByTagName('button')[0]

btn.onclick = function(){

test.style.display = 'none'

}

//当然,也可以让这个按钮失去焦点的时候隐藏test的div

btn.onblur = function(){

test.style.display = 'none'

}

</script>

当你点击这个按钮的时候,可以隐藏div。

这样回答你会觉得太简陋了,或许你需要别的,比如鼠标移除div或者点击其他事件某个条件让其隐藏。