[英]JavaScript - Turning a switch on, then off
I have a light switch image on my website. 我的网站上有一个电灯开关图像。 It triggers a function (using onClick) which makes the whole wrapper div have an opacity of 0.2 giving the effect of lights being off.
它触发一个函数(使用onClick),这使得整个包装器div的不透明度为0.2,从而产生灯光关闭的效果。
So the switch is clicked and the lights are "off", however I cannot work out how to turn them back on. 因此,单击开关并且指示灯“关闭”,但我无法确定如何重新打开它们。
function lightSwitch()
{
document.getElementById("switchoff").style.opacity = '0.2';
}
I am very new to JavaScript so I am confident the solution is simple. 我是JavaScript的新手,所以我相信解决方案很简单。
function lightSwitch()
{
var el = document.getElementById("switchoff"),
opacity = el.style.opacity;
if(opacity == '0.2')
el.style.opacity = '1';
else
el.style.opacity = '0.2';
}
note - this is not tested, the actual value may differ (".2" or "0.2") - you need to test" 注意 - 这没有测试,实际值可能不同(“。2”或“0.2”) - 你需要测试“
If I understood your question right, you want to turn it off after some time. 如果我理解你的问题,你想在一段时间之后将其关闭。
So you should use setTimeout
something like this: 所以你应该使用这样的
setTimeout
:
function lightSwitch()
{
document.getElementById("switchoff").style.opacity = '0.2';
setTimeout(...function to turn it off...,5000); // 5000 mseconds
}
The better approach would be to create a CSS class called 'lightsOut', and add/remove this to your switchoff
element. 更好的方法是创建一个名为'lightsOut'的CSS类,并将其添加/删除到您的
switchoff
元素。
function toggleClass( element, className ) {
element.classList.toggle( className );
}
Note, classList
is not implemented in Internet Explorer, so you would need to reference Eli Grey's polyfill for this. 请注意,
classList
未在Internet Explorer中实现,因此您需要为此引用Eli Gray的polyfill 。 In order to use this function, you pass it an element and a class name. 为了使用此函数,您可以传递一个元素和一个类名。 So to use it again an element with the id
switchOff
, we could do the following: 因此,要再次使用具有id
switchOff
的元素,我们可以执行以下操作:
toggleClass( document.getElementById("switchOff"), 'lightsOut' );
You could give the wrapper div a class in CSS for "on" and another for "off" then toggleClass with JQuery. 您可以在CSS中为包装器div提供一个“on”,另一个用于“off”,然后使用JQuery设置toggleClass。
$(document).ready(function () {
$(".switchClass").click(function () {
$(this).toggleClass("off");
return false;
});
});
CSS: CSS:
div.switchClass{
//Insert your own look and feel
}
div.off.switchClass{
//Same style as div.switchClass except change the opacity
opacity: 0.2;
}
Something like this should work. 这样的事情应该有效。
function lightSwitch() {
var lightSwitch = document.getElementById("switchoff");
if(lightSwitch.style.opacity != "0.2") //If the div is not 'off'
{
lightSwitch.style.opacity = '0.2'; //switch it 'off'
}
else
{
lightSwitch.style.opacity = '1.0'; // else switch it back 'on'
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.