如何在用户脚本中切换一组按钮,当单击一个按钮?



这可能是不好的措辞,所以我会尽量解释得更好。

我试图创建一个用户脚本,将,当一个按钮被点击,显示一组其他按钮点击做该按钮下面的各种事情。然后,在再次点击按钮时,其他按钮集将消失。像一个可切换的下拉菜单。

当前,用户脚本是这样的:

// ==/UserScript==
var menuButton       = document.createElement ('div');
menuButton.innerHTML = '<button id="mainButton" type="button">'
+ 'Glass</button>'
;
menuButton.setAttribute ('id', 'myContainer');
document.body.appendChild (menuButton);
//Click listener
document.getElementById ("mainButton").addEventListener (
"click", openStuff, false
);
function openStuff (zEvent) {
/*--- Dummy action, just adds a line of text to the top
of the screen.
*/
var menuButton       = document.createElement ('p');
menuButton.innerHTML = 'Clicked.';
document.getElementById ("myContainer").appendChild (menuButton);
}
// Style
GM_addStyle ( `
#myContainer {
position:               absolute;
top:                    0;
left:                   0;
font-size:              20px;
z-index:                1100;
}
#mainButton {
cursor:                 pointer;
}
#myContainer p {
color:                  black;
}
` );

目前,它只是在点击按钮时在按钮下方添加了一个透明的虚拟文本行。我没有CSS的经验(从指南中复制/粘贴样式),我的JS经验来自Node.js,所以我非常,非常迷失在这里。如有任何帮助,我将不胜感激。

更新帖子:

  1. 你现在可以复制和粘贴解决方案。我们已经将css和js直接添加到html文件中。注意,样式标签放在标题部分而脚本标签放在底部就在结束正文标签

    之前
  2. 让我们仔细检查一下css和js.
    a)我们将容器的高度设置为视图的高度。严格来说,我们不必这样做,但我想显示对齐
    b)我们设置显示为flex。谷歌flexbox了解更多,但简而言之,这解决了很多问题,使定位元素变得非常容易
    c)我们将flex方向设置为column,这意味着容器中的直接子元素将沿着列流动,而不是穿过行
    d) justify-content:center沿长轴对齐中心。对齐-项目:中心沿小轴向中心对齐。轴是列和行。Flex-direction定义了主轴。
    e)我们开始将#buttons display设置为none以隐藏它
    f) #buttons。Showme表示当元素#button具有。Showme

    类时

js非常简单。唯一需要注意的是button . classlist .toggle("showme");它只是在单击时切换(添加和删除)类。

让我知道这是否有意义或者我们可以做一个缩放调用来查看更详细的内容

<!DOCTYPE html>
<html>
<head>
<title>help</title>
<style>
#container {
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border: solid 1px black;
flex-direction: column;
}
#buttons {
display: none;
}
#buttons.showme {
display: block;
}
</style>
</head>
<body>
<div id='container'>
<div>
<button onclick='toggleMe()'>click me</button>
</div>
<div id='buttons'>
<button onclick='dostuff(0)'>button 1</button>
<button onclick='dostuff(1)'>button 2</button>
</div>
</div>
<script>
function toggleMe() {
var buttons = document.getElementById('buttons')
buttons.classList.toggle("showme");
}
function dostuff(idx) {
if (idx == 0) alert("button 1 action")
else alert("button 2 action")
}
</script>
</body>
</html>

最新更新