首页 > 解决方案 > 我怎样才能让一个按钮在相反的方向做多项事情

问题描述

barsButton.onclick = function xtranslate(){
    aside[0].style.transform = "translateX(0px)"
    stories.style.marginLeft = "0px";
}

如何单击按钮两次,以便下次将 x 转换为 250px?

标签: javascripthtmlcssbutton

解决方案


您可以使用变量并使用条件(三元)运算符更新其值:

var toTranslate = '0px';
barsButton.onclick = function xtranslate(){
  aside[0].style.transform = `translateX(${toTranslate})`;
  stories.style.marginLeft = "0px";
  toTranslate = toTranslate == '0px' ? '250px' : '0px';
}

推荐阅读