我是编码的新手,我正在尝试创建一个函数,每次单击一个按钮时(类似于楼梯设计(,可以逐步降低2行的不透明度。这是我到目前为止的功能:
this.options.events['click button'] = function() {
document.querySelector('#color_bottom').style.opacity = 0.7
document.querySelector('#color_right').style.opacity = 0.7
};
上面的功能将两行(#COLOR_RIGRT(和(#COLOR_BOTTOM(的不透明度从1更改为1.7。但是我需要提供一个函数,该功能每次点击按钮时,都会逐步将不透明度SAVE缩短为0.1。
您的所有帮助将非常感谢!预先感谢您!
您可以使用初始值1
维护一个全局变量。每次单击按钮时,0.1
降低该变量。
演示:
let start = 1;
function increaseOpacity() {
start -= 0.1;
document.querySelector('#color_bottom').style.opacity = start;
document.querySelector('#color_right').style.opacity = start;
};
<button type="button" onclick="increaseOpacity()">Decrease</button>
<div id="color_bottom">color_bottom</div>
<div id="color_right">color_right</div>
您可以将两行的引用存储在数组中,设置默认的不透明度值,然后在每个按钮上降低不透明度:
const step = 0.1
const lines = ['color_bottom', 'color_right']
.map(id => document.getElementById(id))
.map(el => {
el.style.opacity = 1
return el
});
document.getElementsByTagName('button')[0].addEventListener('click', () => {
lines.forEach(line => {
line.style.opacity -= step
})
});
<p id="color_bottom">Line 1</p>
<p id="color_right">Line 2</p>
<button>Reduce Opacity</button>
只是一个小例子。您可以根据需要更改逻辑。
const sub = 0.1;
var main = 1;
this.options.events['click button'] = function() {
if (main > 0) {
document.querySelector('#color_bottom').style.opacity = main - sub;
document.querySelector('#color_right').style.opacity = main - sub;
} else {
main = 1;
}
};
您可以降低行的stroke-opacity
属性的值:
let lines = document.querySelectorAll("line");
let so = 1;//the initial stroke opacity is set to 1
theButton.addEventListener("click",()=>{
if(so > 0){so -=.1;// if the stroke opacity is greater than 1 decrease it
lines.forEach(l=>{// reset the stroke-opacity attribute of the lines
l.setAttributeNS(null,"stroke-opacity",so)
})
}
})
line{stroke:black}
svg{border:1px solid; stroke-width:5; width:90vh;}
<p><button id="theButton">theButton</button></p>
<svg viewBox="0 0 100 100" >
<line x1="10" y1="90" x2="85" y2="90" stroke-opacity="1" />
<line y1="10" x1="90" y2="85" x2="90" stroke-opacity="1" />
</svg>
const button = document.querySelector('.example');
let opacity = 1;
button.addEventListener('click', function() {
opacity -= 0.2;
this.style.opacity = opacity;
});
.example {
background-color:blue;
border: none;
padding: 10px 20px;
}
<button class="example">Button</button>