当在Javascript中选择两个按钮时,如何使条件发生?

时间:2018-03-25 15:25:53

标签: javascript html css

如何在Javascript中编写内容,以便在按下两个按钮时发生一件事?

例如,我想要这样的东西

<button>A</button>
<button>B</button>
<img id = "pics" src = "/randompicture.gif">

在JS中,我希望能够在选择按钮A和B时显示某些内容。

If(button A is hit AND button B is hit){
then this happens, 
such as document.getElementById("pics").visibility = "hidden"}

谢谢

PS:抱歉语法错误。我是HTML,CSS和JS的新手。非常感谢任何帮助。

编辑:通过&#34;选择&#34;,我的意思是当两个按钮至少被按下一次

编辑2:刚刚在repl.it尝试了@ Khauri McClain的事件听众建议。它似乎有效,我得到了我想要的东西。这是我写的

document.getElementById("buttonWithFirstId").addEventListener("click", function(){
     document.getElementById("buttonWithSecondId").addEventListener("click", function(){
         document.getElementById("imageId").style.visibility = "visible"
     });
});

编辑3:哇,似乎有很多方法可以做到这一点。我很高兴尝试这些。感谢您提供所有这些不同的建议。

感谢大家的建议。

4 个答案:

答案 0 :(得分:2)

您可以使用添加/删除到每个按钮的CSS类作为&#34;标记&#34;至于是否点击了按钮。然后,使用 Array.every()] 1 方法(检查每个按钮是否包含该类)。

注意:您设置visibility的代码不正确。您无法直接从DOM对象访问CSS属性,您必须首先访问DOM对象的.style属性。通常,提前设置CSS类并从元素中应用或删除类更好。

因此,当您想要访问元素所具有的类时,可以使用 .classList 属性:

element.classList.add("className")      // adds the class
element.classList.remove("className")   // removes the class
element.classList.contains("className") // returns true/false

无论你需要点击多少个按钮,这个解决方案都会有效。我已经添加了一些按钮来显示这个。我还添加了一些额外的CSS视觉指示器。

&#13;
&#13;
// Get all related buttons into an array
var btns = Array.prototype.slice.call(document.querySelectorAll(".hit"));
var img = document.getElementById("pics"); // Get reference to image

// Loop over the button array
btns.forEach(function(btn){

  // Set up a click event handler for each button
  btn.addEventListener("click", function() {
    // Add or remove a CSS class that tracks the current "hit" state of the button
    // and creates a visual cue as to its state based on whether the class is already applied.
    this.classList.contains("clicked") ? 
      this.classList.remove("clicked") : this.classList.add("clicked");

    // If all the buttons have the clicked class hide the image otherwise don't
    btns.every((b) => { return b.classList.contains("clicked"); }) ?
      pics.classList.add("hidden") : pics.classList.remove("hidden");      
  });
});
&#13;
/* These pre-made classes will be applied/removed as necessary. */
.clicked { box-shadow:0 0 5px rgba(255, 0, 0, .5) }
.hidden  { visibility:hidden; }
&#13;
<button class="hit">A</button>
<button class="hit">B</button>
<button class="hit">C</button>
<button class="hit">D</button>
<img id = "pics" src = "/randompicture.gif" alt="Image Here">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以跟踪按钮的状态。请注意,以下实现允许用户在单击和未单击之间切换每个按钮的状态。如果您希望在用户单独点击该按钮后再次点击该按钮,则只需将state[buttonClicked] = !state[buttonClicked]的行更改为state[buttonClicked] = true

const state = {A: false, B: false};

addEventListener('click', (e) => {
   const buttonClicked = e.target.innerHTML;
   state[buttonClicked] = !state[buttonClicked];
  
   console.log(Object.values(state));
  
   if(Object.values(state).includes(false)) {
     console.log('not all buttons are clicked');
   } else {
     console.log('all buttons are clicked');
     // Do what you got to do here
     document.getElementById("pics").style.visibility = "hidden";
   }
});
<button>A</button>
<button>B</button>
<br/>
<img id = "pics" src ="http://placehold.it/200x200" />

答案 2 :(得分:0)

您可以通过在阵列中添加/删除按钮来跟踪选择的按钮。当两个按钮都在阵列中时,请执行您的操作。

如果数组不在数组中,则会将该按钮添加到数组中。如果再次单击该按钮并且它在阵列中,则将被删除。

let clicked = []

Array.from(document.querySelectorAll('button')).forEach(btn => {
  btn.addEventListener('click', e => {
    // The clicked button
    let target = e.currentTarget
    // Test if the button is in the array
    let idx = clicked.indexOf(target)
    // If it isn't in the array add it
    if (idx == -1) clicked.push(target)
    // Otherwise remove it
    else clicked.splice(idx, 1)
    
    // Test the length of the array.
    // Note: there might be a more dynamic way to do this
    // however, this is the simplest way.
    if (clicked.length == 2) {
      myAction()
    }
  })
})

function myAction() {
  console.log('both buttons clicked!')
}
<button id="a">A</button>
<button id="b">B</button>

答案 3 :(得分:-1)

尝试此功能添加:

function clickedbutton(e) {
  /* Check if button has class selected */
  if (e.classList.contains("selected")) {
    e.classList.remove("selected");
    /* removit if clicked twice */
  } else {
    /* Addit if not */
    e.className += " selected";
  }
  /* loop trow all button */
  var btn = document.getElementsByTagName("button");
  var i;
  var check=0;
  for (i = 0; i < btn.length; i++) {
    if (btn[i].classList.contains("selected")) {
      check++;
    } else {
      check--;
    }
  }
  console.log(check);
  /* if the button has the class selected then change pic src */
  if (check == 2) {
    document.getElementById("pics").src = "https://media.gadventures.com/media-server/cache/a4/b7/a4b727085661bdaa6cc94e84fbe21039.jpg";
  } else {
    document.getElementById("pics").src = "http://artofabsence.com/wp-content/uploads/2012/09/camel-ride1.jpg";
  }
}
.selected {
  border: 1px solid #999999;
  background-color: #cccccc;
  color: #666666;
}

img {
  width: 150px
}
.as-console-wrapper {
    max-height: 50px !important;
}
<button onclick="clickedbutton(this);">A</button>
<button onclick="clickedbutton(this);">B</button>
<img id="pics" src="http://artofabsence.com/wp-content/uploads/2012/09/camel-ride1.jpg">