按钮点击有两个功能

时间:2017-11-09 00:36:18

标签: javascript jquery html css

function myFunction() {
  document.getElementById("tt").style.marginTop = "50px";
  document.getElementById("tt").style.marginTop = "80px";  
}
<div class="switcher" style="margin-top: 30px;background-color: #430000;width: 300px;height: 300px;" id="tt">
  <button id="quick-search-switcher" type="button" onclick="myFunction()">Find a doctor</button>
</div>

我需要一些帮助,我的代码让第一次单击边缘上的按钮 - 顶部容器div 30px和第二次单击-30px,但它不起作用请帮助我使用此代码。

3 个答案:

答案 0 :(得分:1)

您可以使用标记来指示您要执行的操作,并相应地向上或向下移动。

&#13;
&#13;
var switcherAtTop = true;
var elem = document.getElementById('tt');

elem.addEventListener(
  'click',
  function() {
    if(switcherAtTop) {
      document.getElementById("tt").style.marginTop = "80px";
      switcherAtTop = false;
    } else {
      document.getElementById("tt").style.marginTop = "50px";
      switcherAtTop = true;
    }
  }
)
&#13;
.switcher {
  margin-top: 30px;
  background-color: #430000;
  width: 300px;
  height: 300px;
}
&#13;
<div class="switcher" style="" id="tt">
  <button id="quick-search-switcher" type="button">Find a doctor</button>
</div>
&#13;
&#13;
&#13;

也就是说,根据您的使用情况,如果一个按钮执行多项操作,则可能会让用户感到有些困惑。你可能最好有两个按钮,不同的事件监听器(和标签文本)。然后你可以根据需要显示和隐藏它们。

答案 1 :(得分:1)

我是jQuery的粉丝。

这是我的解决方案(通过使用2个类并切换它们):

$('#quick-search-switcher').click(function () {
  $('.switcher').toggleClass('first').toggleClass('second');
});
.first {
  margin-top: 60px;
}

.second {
  margin-top: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="switcher first" style="background-color: #430000; width: 300px; height: 300px;" id="tt">
  <button id="quick-search-switcher" type="button">Find a doctor</button>
</div>

答案 2 :(得分:0)

你可以一般解决这个问题,方法是在一个函数中包含一个你想要交替的函数数组(在你的情况下可以是两个,但它可以是任何数字)来调用模数调用新函数的次数的计数。

这将适用于参数化函数,前提是您传递的所有函数都将接受类似的参数。

function alternate(arrayOfFunctions) {
    var counter = 0;
    return function() {
       var f = arrayOfFunctions[counter++ % arrayOfFunctions.length];
       return f.apply(this, arguments);     
    }
}

function doA() { console.log(doA.name);}
function doB() { console.log(doB.name);}
function doC() { console.log(doC.name);}

var newFunction = alternate([doA,doB,doC]);

newFunction();  // calls doA
newFunction();  // calls doB
newFunction();  // calls doC
newFunction();  // calls doA again, etc.
相关问题