不能把两个div放在一边

时间:2011-08-28 02:48:49

标签: jquery html css

我在另一个内部有两个div,现在我想把显示名为subMenu的子div出现在div父亲旁边,当事件是div父亲中的mouseEnter prueba时。这个事件很好地解决了我的问题,这是我的库存。我怎么能解决这个问题?

我的HTML

<div id="prueba" class="ui-state-hover" style="width:150px;height:20px;float:left">category
</div>
<div style="float:left"> other thing </div> 

我的Js

$(document).ready(initialize);

function initialize() {
    $('#prueba').hover(showSubMenu, hideSubMenu);
}
function showSubMenu() {
    var subMenu = '<div id="subMenu" class="ui-state-hover" style="width:150px;position:relative;top:0px;left:100%">subCategory</div>';
    $('#prueba').append(subMenu);
}

function hideSubMenu() {
    $("#subMenu").remove();
}

here's my live demo

更新 我不希望文本other thing的div移动他的位置。我希望subMenu出现在这个div上

2 个答案:

答案 0 :(得分:2)

在这里,试试这个。

$(document).ready(initialize);

function initialize() {
    $('#prueba').hover(showSubMenu, hideSubMenu);
}
function showSubMenu() {
    var subMenu = '<div id="subMenu" class="ui-state-hover" style="width:150px; float: left; position: relative; top: -20px; left: 150px;">subCategory</div>';
    $('#prueba').append(subMenu);
}

function hideSubMenu() {
    $("#subMenu").remove();
}

new demo

答案 1 :(得分:2)

不是每次都创建子菜单,而是可以检查它是否存在只是使用它。在hideSubMenu方法或remove中,您只需hide

试试这个

正在使用 demo

  $(document).ready(initialize);

  function initialize() {
    $('#prueba').hover(showSubMenu, hideSubMenu);
  }
  function showSubMenu() {
    if($("#subMenu").length == 0){
       $(document.body).append('<div id="subMenu" class="ui-state-hover" style="width:150px; float: left;">subCategory</div>');
    }
      $("#subMenu").css({
          position:'absolute',
          top: $('#prueba').offset().top,
          left: ($('#prueba').offset().left + $('#prueba').width())
      }).show();
  }

  function hideSubMenu() {
    $("#subMenu").hide();
  }
相关问题