【问题标题】:changing classname within if statement has no visual effect yet the property changes在 if 语句中更改类名没有视觉效果但属性更改
【发布时间】:2013-06-17 10:54:17
【问题描述】:

我有一个简单的 html+javascript 屏幕,在运行时屏幕上有按钮 以前在IE6下能用,现在平台升级到windows 7 + IE9(IE8 comp模式),屏幕全乱码。

这是该功能的一部分

function AttachButton(btn, buttonloc)
{
    var elTr = document.createElement('TR');
    var elTdText = document.createElement('TD');
    elTdText.id= idbase+"text";

    elTr.appendChild(elTdText);
    //*snip*
    //here was code that attaches the TR to the proper table
    //******
    if (elTdText.offsetWidth < 162 && btnText.search("<br>") < 0) {
        elTdText.className = "singlebutton";
    }
    else {
        elTdText.className = "doublebutton";
    }
    if (btn.name == "contact") {
        elTdText.className = "contactbutton";
    }
}

这似乎没有效果。如果我删除这部分代码,页面具有相同的样式。 但是每当我在这个函数的末尾添加 className=className 时,一切都会再次正常工作 像这样:

function AttachButton(btn, buttonloc)
{
    var elTr = document.createElement('TR');
    var elTdText = document.createElement('TD');
    elTdText.id= idbase+"text";

    elTr.appendChild(elTdText);
    //*snip*
    //here was code that attaches the TR to the proper table
    //******
    if (elTdText.offsetWidth < 162 && btnText.search("<br>") < 0) {
        elTdText.className = "singlebutton";
    }
    else {
        elTdText.className = "doublebutton";
    }
    if (btn.name == "contact") {
        elTdText.className = "contactbutton";
    }
    elTdText.className = elTdText.className;
}

我尝试更改代码以使用 setAttribute("class", "singlebutton") 或将 className 存储在字符串中并使用 elTdText.className = classNameVar 但没有效果。 除非我添加看起来很愚蠢的 className = className,否则它不起作用。

【问题讨论】:

  • 其他浏览器会发生什么?这是您的代码还是 IE 的问题?
  • 我猜你正在更改tr 的背景(颜色),它被td 的背景覆盖。但是我仍然无法想象在做elTdText.className = elTdText.className; 时会有什么影响。我们能看到相关的 CSS 吗?
  • 我无法在其他浏览器上测试它。它被用作一种信息亭,其中有太多 IE 特定(遗留)代码
  • 也许我应该描述什么是错的。该类只做位置和样式文本。没有代码,文本就在它应该在上面的图像旁边。这些类名设置颜色、高度、自动换行、顶部、左侧、位置、zindex 和字体系列。我认为主要的变化是将位置设置为 abosulte
  • 我看到,在版本开发的某个阶段,为td 中的元素设置position: absolute 使用table 作为定位父级,旧版本使用td,即@ 内的绝对定位987654330@ 是不可能的。

标签: javascript html css dom classname


【解决方案1】:

据我所知,className 是特定于 IE 的。尝试使用“类”或setAttribute('class', ...)

EDIT既然你试过了,错误可能是因为:

elTdText.className = elTdText.className;

A = A 什么都不做。

【讨论】:

  • 什么?! className 是一个非常特定于浏览器的属性名称。
  • 是时候扩展the knowledge了; )。
  • 也许你应该再读一遍我的问题。我知道这是一段愚蠢的代码,但除非 A=A 存在,否则它不起作用。然而,当我在该行之前发出警报时,该属性是正确的
  • 好吧,我可以一遍又一遍地阅读它,我永远无法理解您为什么要这样做elTdText.className = elTdText.className;,以及为什么这样做会改变任何事情。 :o
  • @Teemu 如果成员名称不再匹配属性名称(即 id -> id, class -> className),则不再一致,可能导致错误和不直观的代码等,不应该不再使用。
猜你喜欢
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多