我需要一个用于 Tampermonkey 脚本的按钮

问题描述

我需要一个交替运行这两个代码的按钮:

document.querySelector('.top-left').style.width = '340px'

document.querySelector('.top-left').style.width = '0px'

点击一次执行一个,再次点击执行另一个

这是一个隐藏页面上一列的按钮。

有人可以帮我吗? 我不明白。 我创建了按钮,但无法向其添加功能

解决方法

<button onclick="myFunction">Click me</button>
const myFunction = (event)=> {
  const elm= document.querySelector('.top-left');
  if(elm.style.width==="340px")
    elm.style.width = '0px';
  else
    elm.style.width = '340px'
};
,

你想要的是Toggle Class

你的按钮看起来像这样

<button id="button-show-hide">Show/Hide</button>

let el = document.querySelector('.top-left')
let button = document.getElementById('button-show-hide')

button.addEventListener('click',showHide)

function showHide(){
   el.classList.toggle('hide')
}

和 CSS

.top-left .hide {
  width: 0px;
}