简体   繁体   中英

Reorder div using javascript

I am trying to change the order of the div s using JavaScript`. Is this how I can go about it?

<div id="pageWrapper">
    <div id="one">1</div>
    <div id="two">2</div>
    <div id="three">3</div>
    <div id="four">4</div>
</div>

$(document).ready(function(){ 
        $('#pageWrapper').prepend('#three');
        $('#pageWrapper').prepend('#four');

});

You could use this with the window.resize() event if needed (you'd use an else statement to set it back to default as well)

$(document).ready(function(){
    $(window).resize(function(){    
     if ($(window).width() < 980) {
        $('#three').insertBefore('#one');
        $('#four').insertBefore('#two');
     } else {
      // Set back to default, or whatever you like.
     }
    });
});

jsFiddle here.

prepend does not accept a String selector. From the doc :

.prepend( content [,content] )
────────────────────────────────────────────────────────────────
content
Type: htmlString or Element or Array or jQuery

DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.

You have to pass a jQuery object instead:

http://jsfiddle.net/DerekL/eHq2a/

$('#pageWrapper').prepend($('#three'));
$('#pageWrapper').prepend($('#four'));

//or just

$('#pageWrapper').prepend($('#four'), $('#three'));

However, interestingly .prependTo does accept a String selector:

$("#three").prependTo("#pageWrapper");

Please use some responsive design then. In your case, use @media queries in CSS. Way better than doing it in script.

@media screen and (max-width:980px) {
/* your style */
}

If you still prefer to use script, then you can subscribe to the resize event handler like

$( window ).resize(function() {
  if($(window).width()<requiredMinimum)
  {
    //dowhatever
  }
  else
  {
    //revertback
  }
});

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