HTML 元素的 hidden 属性不生效的问题

HTML 元素的 hidden 属性不生效的问题

HTML 中的hidden属性用于显示和隐藏元素,如e.hidden = true。但是当元素设置了display样式时,不论是在元素样式属性style中设置还是在 CSS 类中设置,则hidden属性就会失去作用。所以,要想继续使用 hidden 属性,必须解决display样式的问题。解决问题的代码如下:

Object.defineProperties(HTMLElement.prototype, {
    'hidden': {
        get() {
            return $parseBoolean(this.getAttribute('hidden') ?? false);
        },
        set(hidden) {
            if (typeof(hidden) != 'boolean') {
                hidden = $parseBoolean(hidden, true, this);
            }
            if (hidden) {
                this.setAttribute('hidden', '');
                if (this.style.display != '') {
                    this.setAttribute('style-display', this.style.display);
                    this.style.display = 'none';
                }
                else if (window.getComputedStyle(this).display != '') {
                    this.setAttribute('inbox-display', '');
                    this.style.display = 'none';
                }                
            }
            else {
                this.removeAttribute('hidden');
                if (this.hasAttribute('style-display')) {
                    this.style.display = this.getAttribute('style-display');
                    this.removeAttribute('style-display');
                }
                else if (this.hasAttribute('inbox-display')) {
                    this.style.display = '';
                    this.removeAttribute('inbox-display');
                }
            }
        }
    }
});

以下是代码解释。

  • 使用Object.defineProperties为所有元素HTMLElement重新定义hidden属性,当然使用Object.defineProperty也可以。
  • 当元素的hidden属性值为true时,那么元素上会多一个空值hidden属性,如<p hidden></p>,这就是元素隐藏和显示的标志。可以用setAttribute('hidden', '')进行设置隐藏,当然这个属性无论你设置成什么值元素总会隐藏,所以要用removeAttribute('hidden')取消隐藏。
  • 不能在定义逻辑中使用this.hidden = truethis.hidden = false进行隐藏和显示,会造成堆栈溢出,因为会不断回调自身。
  • 先说隐藏逻辑,即hidden要设置为true时,如果在元素style属性中设置了display样式时,则通过style-display属性暂时存储display的值,因为不知道原本设置的什么值。如果 CSS 类内设置了display样式,用window.getComputedStyle方法可以获得,则设置inbox-display属性,这个值不需要暂存,因为修改不了。
  • 然后显示逻辑,如果有style-display属性,则把这个属性的值重新赋值给style.display即可,需要使用完移除style-display属性。如果有inbox-style属性,则用style.display = ''显示元素,然后移除inbox-display属性。

对于页面初始化时,可以这样做,就是重新设置一遍。

$$('[hidden]').forEach(e => {
        e.hidden = e.getAttribute('hidden');
    });

(本文完)

源文地址 http://www.qross.cn/blog/20220420-hidden

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值