0

对于基于 Blogger的网站,我使用了一个名为“最近的文章”的小部件。这些样式适用于 Firefox 和 Chrome,但不适用于 IE。

我是 Web 开发新手,不懂 JS。

未应用特定 CSS(文章标题):

.bp_item_title {
    margin: 10px 0;
    padding: 0;
    font-family: Tahoma,Geneva,sans-serif;
    font-size: 14px;
} 

我在 IE 上的 firebug 中对此进行了测试,看起来 CSS 样式没有附加到元素上。为什么 IE 不会将这些 CSS 样式传递给元素/小部件?

HTML 片段

<!-- ... -->
<div class="widget-content">
<div id="bp_recent"><div class="bp_item_title"><a href="http://blog.onlinewagerreview.com/2012/05/miami-heat-vs-boston-celtics-game-2.html?utm_source=BP_recent&amp;utm-medium=gadget&amp;utm_campaign=bp_recent" target="_top" title="Miami Heat vs Boston Celtics, Game 2 Free Pick, Prediction">Miami Heat vs Boston Celtics, Game 2 Free Pick, Prediction</a></div>
    if (showThumbs == true && thumbUrl != "") {
        myImage = document.createElement('img');
        myImage.setAttribute("src", thumbUrl);
        if(imgFloat!="none")
        {
        float_clear=true;
        myImage.style.cssFloat=imgFloat;
        myImage.style.styleFloat=imgFloat;
        }
      try{if(myMargin!=0)myImage.style.margin = myMargin+"px";} catch(error){}
        myImage.setAttribute("alt", postTitleOriginal);
        myImage.setAttribute("width", imgDim);
        myImage.setAttribute("height", imgDim);
        myLink = document.createElement('a');
        myLink.setAttribute("href", postUrl+"?utm_source=bp_recent&utm-medium=gadget&utm_campaign=bp_recent");
        myLink.setAttribute("target", "_top");
        myLink.setAttribute("title", postTitleOriginal);
        myLink.appendChild(myImage);

        myDiv = document.createElement('div');
        myDiv.setAttribute("class", "bp_item_thumb");
        myDiv.appendChild(myLink);
        main.appendChild(myDiv);
    }

资源

4

1 回答 1

1

setAttribute()在 IE 中不适用于该style属性。要支持 IE,请使用element.className = 'newClass';. 使用检查class属性是否已设置为非空值并在设置时包含这些值的函数也是一个好主意。例如:

// $el is the element to add $class to
// $class is the string value to append to `class` attribute
function addClass($el, $class) {
 if(!$el){
  return false;
 }
    $c = $el.className;
    if (($c === null) || ($c === '')) {
        $el.className = $class;
    } else if ($c.indexOf($class) === -1) {
        $el.className = $c + ' ' + $class;
    }
}

// $el is the element to remove $class from
// $class is the string value to remove from `class` attribute
function removeClass($el, $class) {
 if(!$el){
  return false;
 }
    $c = $el.className;
    if (($c !== null) && ($c !== '') && ($c.indexOf($class) !== -1)) {
        if ($c.indexOf($class) === 0) $el.className = $c.replace($class, '');
                else $el.className = $c.replace(' ' + $class, ''); 
    }
}

或者简单地将class属性设置为新值(而不是附加新类或删除单个类):

myDiv.className = "bp_item_thumb";

...代替...

myDiv.setAttribute("class", "bp_item_thumb");
于 2012-05-31T18:06:32.170 回答