You need to enable JavaScript to run this app. 为Backbone视图动态添加aria-hidden后屏幕阅读器仍读内容如何解决
优惠活动
大模型
产品
解决方案
定价
更多

为Backbone视图动态添加aria-hidden后屏幕阅读器仍读内容如何解决

问题原因

Backbone的子视图是独立挂载到父容器DOM节点上的,你在父视图模板里写的条件渲染逻辑仅会在父视图首次渲染时生效,后续子视图挂载、页面重新渲染时,要么父容器的属性没有同步更新,要么部分屏幕阅读器会忽略父级的aria-hidden属性,直接读取已挂载的子节点内容。

解决方案

你可以按照以下优先级选择适配方案:

  • 优先处理子视图生命周期,状态变更时直接卸载不需要的子视图,从根源避免内容被屏幕阅读器读取,示例代码如下:
// 父视图render方法内逻辑
render: function() {
  const parentContainer = this.$('#id_of_the_view');
  const isTrue = this.model.get('isTrue'); // 替换为你自己的isTrue取值逻辑

  if (isTrue) {
    parentContainer.hide().attr('aria-hidden', 'true');
    // 卸载已存在的子视图
    if (this.childView) {
      this.childView.remove();
      this.childView = null;
    }
  } else {
    parentContainer.show().attr('aria-hidden', 'false').addClass('otherClasses');
    // 仅在需要展示时初始化挂载子视图
    if (!this.childView) {
      this.childView = new YourChildView();
      parentContainer.append(this.childView.render().el);
    }
  }
  return this;
}
  • 如果业务场景不允许卸载子视图,可以同时给父容器加双重隐藏样式,覆盖所有屏幕阅读器适配规则:
/* 全局通用屏幕阅读器隐藏样式 */
.accessibility-hide {
  display: none !important;
  visibility: hidden !important;
}

模板修改为:

<div id="id_of_the_view" {{#if isTrue}} class="accessibility-hide" aria-hidden="true" {{else}} class="otherClasses" {{/if}}></div>
  • 每次isTrue状态变更时,手动触发父视图的render方法执行,不要依赖模板的自动条件渲染逻辑,确保属性更新及时生效。

内容的提问来源于stack exchange,提问作者Lalaphoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 06:03:03