This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
                                
                                    (9个答案)
                                
                        
                                5年前关闭。
            
                    
我需要使它适用于所有元素:JSFiddle

第一要素

  <p id="tweet1">First long text displayed fully on hover</p>


通过

   var tweet = document.getElementById('tweet1');


第二和第三个元素不起作用:

  <span class="tweet1">Second long text displayed fully on hover</span>

  <span class="tweet1">Third long text displayed fully on hover</span>


JavaScript:

var tweet = document.getElementById('tweet1');
tweet.id = 'tweet1';
tweet.className = 'hiding';

var slide_timer,
    max = tweet.scrollWidth,
    slide = function () {
        tweet.scrollLeft += 2;
        if (tweet.scrollLeft < max) {
            slide_timer = setTimeout(slide, 40);
        }
    };

tweet.onmouseover = tweet.onmouseout = function (e) {
    e = e || window.event;
    e = e.type === 'mouseover';
    clearTimeout(slide_timer);
    tweet.className = e ? '' : 'hiding';
    if (e) {
        slide();
    } else {
        tweet.scrollLeft = 0;
    }
};


的CSS

#tweet1 {
    overflow:hidden;
    white-space:nowrap;
    width:120px;
}
.hiding {
    text-overflow:ellipsis;
}


当我将HTML <p id="tweet1">更改为<p class="tweet1">时,
在CSS #tweet1.tweet1和JS var tweet = document.getElementById('tweet1');var tweet = document.gelElementsByClassName('tweet1');
没有任何反应,第一个元素停止工作。

最佳答案

的HTML
    第一个长文本在悬停时完全显示

<p class="tweet1">Second long text displayed fully on hover</p>

<p class="tweet1">Third long text displayed fully on hover</p>


的CSS

 .tweet1 {
   overflow:hidden;
    white-space:nowrap;
   width:120px;
}
.hiding {
    text-overflow:ellipsis;
}


jQuery / JavaScript

$('.tweet1').addClass('hiding');

var slide_timer,
slide = function (element) {
    element.scrollLeft += 2;
    if (element.scrollLeft < element.scrollWidth) {
        slide_timer = setTimeout(function(){slide(element);}, 40);
    }

};


$('.tweet1').mouseover(function () {
    clearTimeout(slide_timer);
        $(this).removeClass('hiding');
        slide(this);
    });

$('.tweet1').mouseout(function () {
    clearTimeout(slide_timer);
        $(this).addClass('hiding');
        $(this)[0].scrollLeft = 0;
    });


要查看它的实际效果,请查看此jsFiddle

关于javascript - 如何使getElementsByClassName代替getElementById工作? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20557809/

10-10 00:23