简体   繁体   中英

How do I divide a list of LI's with JavaScript?

Let's say my Rails 3 app returns a list of li tags. Think of an image gallery where each li tag contains a small image.

What I want to do is determine the width of the screen, then only show 5-7 images before I move down to the next line.

For example, say I have a wide-screen monitor I might have:

IMG1 IMG2 IMG3 IMG4 IMG5 IMG6 IMG7
IMG8 IMG9 ...

But on a smaller monitor, I would want:

IMG1 IMG2 IMG3 IMG4 IMG5
IMG6 IMG7 IMG8 IMG9 ...

Maybe JavaScript isn't the best way to do this. Would it be better to write some method in Rails?

Thanks for any suggestions.

You should probably just use CSS for this issue. Make the LIs float: left and they adapt to the space available.

Using CSS only, you could set the <li> elements to display: inline , and then use relative widths (percentages) to make them fill the space. To change the number of elements per line, @media queries will help:

li {
    display: inline;
}

@media (max-width: 400px) {
    li {
        width : 33%;  /* three per line */
    }
}
@media (max-width: 600px) {
    li {
        width : 25%; /* 4 */
    }
}
@media (min-width: 1000px) {
    li { 
        width : 20%;
    }
}

there will be other styles you'll have to reset to make that work exactly right (removing padding, etc), but that might be a good start.

You can do it with CSS easily, set all the elements to display:inline; Put them all in a with a percent based width (or just use the entire width)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM