简体   繁体   中英

Changing element position inside parent div using jquery

Inside my div class="box" there is heading H1 and logo div . HTML is shown below so logo image is below heading text. Now I want to shuffle position of H1 and logo div using jquery (using ternary or if else) to position heading below logo div and vice versa.

HTML:

<div id="block">    
     <div id="box">    
       <h1><a>HEADING TEXT</a></h1>    
       <div class="logo">
          <a>
             <img src="images/logo.png">" alt="" width="150" height="150"/>
          </a>
       </div>    
     </div>
 </div>

CSS:

#box {
    width: 230px;
    height: 500px;
}

#logo {
    width: 230px;
    height: auto;
}

#logo img {
    width: 150px height:150px;
}

How I can shuffle position

See a demo

var $box = $('#box').click(function(){
    var $this = $(this), $h1 = $box.find('h1'), $div = $box.find('.logo');

    if($h1.index() < $div.index()){
        $h1.detach().insertAfter($div)
    } else {
        $h1.detach().insertBefore($div)
    }
})

Demo: Fiddle

您可以为此使用jquery的.detach()和.insertAfter()方法。

$("#box h1:first").detach().insertAfter(".logo");

Since in box we have just the text and logo, we can switch than just using prepend function:

var logo = $('#box .logo'),
    h1 = $('#box h1'),
    box = $('#box'),
    isLogo = false,
    selector = function(){
         isLogo = !isLogo;
         return isLogo? logo : h1;
    };



setInterval(function(){

    var toSwitch = selector();
    toSwitch.fadeOut('slow', function(){
        toSwitch.prependTo(box).fadeIn('slow');
    })

    //or just 
    //selector().prependTo(box);
}, 3000)

JSFIDDLE

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