Setting width of multiple elements with same class depending on their number

心已入冬 提交于 2019-12-24 20:48:39

问题


I'm experiencing a problem similar with one I had before. I'm trying to give multiple elements a width depending on how many of them exist.

Say I have 5 elements, their widths have to be 20%, if I have 4 25% etc. (width = 100 / n)

I thought this would work, but it doesn't:

    if ($(window).width() <= 960) {

        $("aside.widget").css("width", function(){
            var widgetLength = $("section#secondary").children("aside.widget").length();
            return 100 / widgetLength + "%"
        });
    }

Nor does:

    if ($(window).width() <= 960) {         
        $("aside.widget").css("width", 100 / widgetLength + "%");
    }

Console returns: Uncaught TypeError: Property 'length' of object [object Object] is not a function

Any thoughts? Thanks.


回答1:


They should both work just fine, but length is not a function, so you need to change this:

var widgetLength = $("section#secondary").children("aside.widget").length();

to this:

var widgetLength = $("section#secondary").children("aside.widget").length;

then both the methods in your question will work!



来源:https://stackoverflow.com/questions/12123267/setting-width-of-multiple-elements-with-same-class-depending-on-their-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!