我必须单击两次才能运行jQuery函数

时间:2017-01-13 08:14:05

标签: jquery html css

当我的网站上的屏幕分辨率达到手机或iPad的宽度时,我会将其变成带有图像的条形单击时我想要一个条形图随着导航条下拉但更容易然而,必须单击两次才能运行该函数。如果有人可以帮助它会很棒! :)



function onTogglePan() {
  var clicks = $(this).data('clicks');
  if (clicks) {
    $("#navhide").css("display", "block");
    $("#navhide").css("visibility", "visible");
  } else {
    $("#navhide").css("display", "none");
    $("#navhide").css("visibility", "hidden");
  }
  $(this).data("clicks", !clicks);
};

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navshowmenu">
  <a id="showmenu" onclick="onTogglePan()">
    <img src="ico/ham.png" style="height: 52px; width: 52px; margin-left: 10px; margin-top: 10px; display: inline-block;">
  </a>
  <button onclick="onTogglePan()">Drop</button>
</div>
<div id="navhide">I am #navhide</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

你是说这个吗?(只是一个css解决方案)

&#13;
&#13;
function onTogglePan() {
  var clicks = $(this).data('clicks');
  if (clicks) {
    $("#navhide").css("display", "block");
    $("#navhide").css("visibility", "visible");
  } else {
    $("#navhide").css("display", "none");
    $("#navhide").css("visibility", "hidden");
  }
  $(this).data("clicks", !clicks);
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navshowmenu">
  <a id="showmenu" onclick="onTogglePan()">
    <img src="ico/ham.png" style="height: 52px; width: 52px; margin-left: 10px; margin-top: 10px; display: inline-block;">
  </a>
  <button onclick="onTogglePan()">Drop</button>
</div>
<div id="navhide" style="  visibility: hidden;">I am #navhide</div>
&#13;
&#13;
&#13;

如果是这样,请高兴我,我不明白问题是关于双击还是关于导航菜单

答案 1 :(得分:0)

我仍然不确定你在寻找什么,但我试着解释

这就是您所做的:

function onTogglePan() {
    // since you don't set data-clicks per default the 
    // first value of clicks is false
    var clicks = $(this).data('clicks');
    if (clicks) {
        // clicks is true - show the bar
        // this happens on second click
        $("#navhide").css("display", "block");
    } else {
        // clicks is false (hide the bar)
        // this happens on first click
        $("#navhide").css("display", "none");
    }
    $(this).data("clicks", !clicks);
};

我猜你想要反过来。因此,如果您只是使用if (!clicks)而不是if (clicks)来切换条件,那么它应该可行。无论如何,您可能不需要这样的属性。您还可以查看可见性:

function onTogglePan() {
    var nav = $('#navhide');
    // if is visible hide, otherwise show
    var vis = (nav.is(':visible')) ? 'none' : 'block';
    nav.css("display", vis);        
};

查看您的updated example here

答案 2 :(得分:0)

只需删除[a]标记,然后在您的[按钮]标记上添加id =“showmenu”