【问题标题】:jquery .toggleClass on click using multiple IDs点击使用多个ID的jquery .toggleClass
【发布时间】:2018-11-15 10:30:33
【问题描述】:

我正在尝试使用 jquery 切换 <html> 标签的滚动条。

我希望当我点击按钮#foo 时滚动条消失,我希望它在我点击#bar1 时重新出现。

$('#foo').click(function() {
  $('html').toggleClass("hidescroll");
});
$('#bar1').click(function() {
  $('html').toggleClass("hidescroll");
});
.hidescroll{
  overflow-y: hidden !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">foo</div>
<div id="bar1">bar1</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

当我点击#foo时它会消失,但它不会在#bar1上重新出现,但是当再次点击#foo时它会重新出现。

【问题讨论】:

  • .hidescroll 的 CSS 是什么
  • 你能做一个js小提琴吗?根据您的代码,它不会有任何问题
  • 它确实有效 -> jsfiddle.net/fyedavht。你的 html 中是否肯定有相同的 foobar1 id?
  • 它的工作兄弟
  • 你的例子在这里显然有效

标签: javascript jquery html css


【解决方案1】:

你可以这样做...使用 add 和 removeClass 而不是 toggleClass...

$('#foo').click(function() {
  $('html').addClass("hidescroll");
});

$('#bar1').click(function() {
  $('html').removeClass("hidescroll");
});
.hidescroll {
  overflow:hidden;
}
#main {
  width:100%;
  height:2000px;
  float:left;
}
#foo {
  float:left;
  width:100px;
  height:50px;
  background-color:red;
  margin-right:15px;
}
#bar1 {
  float:left;
  width:100px;
  height:50px;
  background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div id="foo"></div>
<div id="bar1"></div>
</div>

【讨论】:

  • 它使用overflow: hidden 而不是overflow-y: hidden 工作。谢谢。
【解决方案2】:
$("#foo, #bar1")

是您要查找的选择器。

片段:

$('#foo, #bar1').click(function() {
  $('html').toggleClass("hidescroll");
});
.hidescroll {
  overflow:hidden;
}
#main {
  width:100%;
  height:2000px;
  float:left;
}
#foo {
  float:left;
  width:100px;
  height:50px;
  background-color:red;
  margin-right:15px;
}
#bar1 {
  float:left;
  width:100px;
  height:50px;
  background-color:blue;
}
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<div id="main">
<div id="foo"></div>
<div id="bar1"></div>
</div>

【讨论】:

    【解决方案3】:

    只是一种选择

    bar =v=> $('html').css('overflow',v)
    $('#foo').click(()=> bar('hidden'))
    $('#bar1').click(()=> bar('scroll'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多