在多个元素上运行JavaScript函数

Run JavaScript function on multiple elements..?

本文关键字:运行 JavaScript 函数 元素      更新时间:2023-09-26

我是JavaScript(当然还有jQuery)的新手,所以我正在寻求一点帮助…这个JavaScript函数根据容器的div改变字体大小。

http://jsfiddle.net/pthjU/

我需要它的工作为所有div(某一类,最终)-但它只从第一个抓取信息,并根据那一个调整它们的大小。任何想法吗?

不是在寻找复制/粘贴的答案,我想正确地完成这个。谢谢!

既然你想独立处理每个元素,你可以在你的插件中这样做,通过在那里做一个.each()循环,而不是这样:

$.fn.textfill = function(options) {
    var fontSize = options.maxFontPixels;
    var ourText = $('span', this);
    var maxHeight = $(this).height();
    var maxWidth = $(this).width();
    var textHeight;
    var textWidth;
    do {
        ourText.css('font-size', fontSize);
        textHeight = ourText.height();
        textWidth = ourText.width();
        fontSize = fontSize - 1;
    } while (textHeight > maxHeight || textWidth > maxWidth && fontSize > 3);
    return this;
}

应该是这样的:

$.fn.textfill = function(options) {
    return this.each(function() {
        var fontSize = options.maxFontPixels;
        var ourText = $('span', this);
        var maxHeight = $(this).height();
        var maxWidth = $(this).width();
        var textHeight;
        var textWidth;
        do {
            ourText.css('font-size', fontSize);
            textHeight = ourText.height();
            textWidth = ourText.width();
            fontSize = fontSize - 1;
        } while (textHeight > maxHeight || textWidth > maxWidth && fontSize > 3);
    });
};

你可以在这里测试


作为题外话,从老方法…this已经是一个插件内部的jQuery对象(注意我是如何直接调用.each()的),没有必要把它包装在另一个jQuery对象(克隆它)。你需要包装它在我的第二个例子循环,因为在.each()你指的是单独的DOM元素,而不是jQuery对象。

add .each() into

$('.post').each().textfill({ maxFontPixels: 500 }); <--- not sure if this works.. but
$('.post').each(function(){
    jQuery(this).textfill({ maxFontPixels: 500 });
});

一定可以。

艾伦