我有这段代码,向下滚动时会显示“页面顶部”链接:

window.addEvent('load', function() {
                new JCaption('img.caption');
            });
function fade_me(num){
    var smoothtop=document.id('smoothtop');
    if(smoothtop){smoothtop.fade(window.getScrollTop()<250?0:num);}
}
window.addEvent('domready',function(){
    var scroll=new Fx.Scroll(window,{
        'duration': 500,
        'transition':   Fx.Transitions.Bounce.easeInOut,
        'wait':     false
    });
    var smoothtop=new Element('div',{
        'id':       'smoothtop',
        'class':    'smoothtop',
        'style':    'position:fixed; display:block; visibility:visible; zoom:1; opacity:0; cursor:pointer; right:5px; bottom:5px;',
        'title':    '',
        'html':     '',
        'events':{
            mouseover: function(){fade_me(1);},
            mouseout: function(){fade_me(0.7);},
            click: function(){scroll.toTop();}
        }
    }).inject(document.body);


    document.id('smoothtop').setStyle('opacity','0');
});
window.addEvent('scroll',function(){fade_me(0.7);});

//this is what I added
var ii = document.getElementById('smoothtop');
ii.childNodes[0].nodeValue = '<i class="icon icon-chevron-up"></i>';
//these two lines


如您所见,代码生成了一个ID为smoothtop的div。它有向上箭头的图片指示页面的顶部。相反,我想使用BootStrap的glyphicon

<i class="icon icon-chevron-up"></i>


我试图将此内容添加到div smoothtop中。当我使用FireBug检查代码时,它说:

TypeError: ii is null

var ii = document.getElementById('smoothtop');


我不知道我在哪里和/或哪里做错了?我想问一下如何将<i></i>添加到js创建的div中?

最佳答案

以您的示例为例,最简单的方法是在创建Element时使用html属性:

var smoothtop=new Element('div',{
    'id':       'smoothtop',
    'class':    'smoothtop',
    'style':    'position:fixed; display:block; visibility:visible; zoom:1; opacity:0; cursor:pointer; right:5px; bottom:5px;',
    'title':    '',
    'html':     '<i class="icon icon-chevron-up"></i>', // <-- right here
    'events':{
        mouseover: function(){fade_me(1);},
        mouseout: function(){fade_me(0.7);},
        click: function(){scroll.toTop();}
    }
}).inject(document.body);

07-24 09:44
查看更多