简体   繁体   中英

How to display the postition absolute div as the position relative div?

I have a parent div "total" in which, there are two children divs namely, "some" and "box". When I click on the link in the div "some" (child-1), the "box"(child-2) must be displayed with width: 100%; and if I click on other parent link, the current "box" (child-2) must be hidden. Also, the paragraph tag must not be hidden when the click button is clicked(as in position: relative).

Here is the fiddle to work this out.

The following lines are the code I tried.

 $('.box').hide();
$(".click-btn").on('click', function() {
    $('.box').hide();
   $(this).parent().parent().children(".box").toggle(1000);
});

check this if it solve your problem jsfiddle

i added this

$('.box').hide();
$(".click-btn").on('click', function() {
    $('.box').hide();
   $(this).parent().parent().children(".box").toggle(1000);
});

add the css

.box {
  width: 100%;
  float: left;
  position: absolute;
  height: 200px;
  background: orange;
  top: 70px;
  left: 0px;
  clear: both;
}

My solution would be putting each .box outside of the floating .single and reference them with an data attribute.

<div class="total">
    <div class="single">
        <div class="some"><a class="click-btn" href="#" data-box="box1">click</a></div>
    </div>

    <div class="clearfix"></div>

    <div class="box" data-id="box1">Box 1</div>
</div>

And the box css

.box {
  width: 100%;
  height: 200px;
  background: orange;
  display:none;
}

If you set the display none in css you don't have to use $('.box').hide(); on dom ready.

Since you hide all .box elements on click, the toggle function won't work. To toggle the box if you click the active link again you can use the .not() function of jQuery which will take out an element of the collection.

Alltogether the JS would look like:

$(".click-btn").on('click', function(e) {
    e.preventDefault();
    var boxId = $(this).data('box');
    var activeBox = $('[data-id="'+boxId+'"]');
    $('.box').not(activeBox).hide();
    activeBox.toggle(1000);
}); 

I'm using e.preventDefault(); what will prevent the default browser action for clicking a link.

Here is a fiddle: http://jsfiddle.net/mrvtwpjp/40/

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