无法在DIV上使用JavaScript执行CSS代码

Cannot execute CSS code using JavaScript on a DIV

本文关键字:JavaScript 执行 CSS 代码 DIV      更新时间:2024-03-30

当用户单击中间的div(蓝色)时,我想使用左右div来提供滑动效果。但它不起作用。

脚本代码不起作用。我认为有一些错误。

当我在样式表中使用悬停时,它也不起作用。我的意思是,我在id internal/outer/power上使用了悬停,这将改变id左右的css属性,以创建滑动过渡效果。但它没有起作用。但当我使用容器悬停而不是上面的id时,滑动效果就起作用了。我很沮丧,因为这对我来说毫无意义。

<script type="text/javascript" >
	function slide()
	{
		document.getElementById("left").style.left = -100% ;
		document.getElementById("right").style.right = -100% ;
	}
</script>
html,body{
	height: 100%;
	width: 100%;
	margin: 0;
    max-width: 100%;
    overflow-x: hidden;
}
#container {
	height: 100%;
	width: 100%;
	margin: 0;
	position: absolute;
}
#left {
	left: 0px;
	margin-left: 0%;
	position: absolute;
	height: 100%;
	width: 50%;
	background-color: yellow;
	transition: left ease-out 3s;
	
}
#right {
	right: 0px;
	margin-left: 50%;
	position: absolute;
	height: 100%;
	width: 50%;
	background-color: green;
	transition: right ease-out 3s;
}
#outer{
	z-index: 5;
	margin-left: 47.5%;
    margin-top: 25%;
	width: 5%;
	position: absolute;
}
#inner {
	z-index: 5;
	width: 100%;
	height: 100%;
	padding-bottom: 100%;
    border-radius: 50%;
    background-color: blue;
   
}
#power {
	z-index: 5;
	position: absolute;
	width: 100%;
	height: 100%;
	
}
<html>
<head>
	<link rel="stylesheet" type="text/css" href="design.css">
	<title></title>
</head>
<body>
<div id="container">
	<div id="outer">
	<div id="inner" >
	<a href="javascript:slide()">
		<img id="power" src="off.png">
 	</a>
	</div>
	</div>
	<div id="left"></div>
	<div id="right"></div>
</div>
</body>
</html>

CSS效果的值需要在引号中。

	function slide()
	{
		document.getElementById("left").style.left = "-100%";
		document.getElementById("right").style.right = "-100%" ;
	}
html,body{
	height: 100%;
	width: 100%;
	margin: 0;
    max-width: 100%;
    overflow-x: hidden;
}
#container {
	height: 100%;
	width: 100%;
	margin: 0;
	position: absolute;
}
#left {
	left: 0px;
	margin-left: 0%;
	position: absolute;
	height: 100%;
	width: 50%;
	background-color: yellow;
	transition: left ease-out 3s;
	
}
#right {
	right: 0px;
	margin-left: 50%;
	position: absolute;
	height: 100%;
	width: 50%;
	background-color: green;
	transition: right ease-out 3s;
}
#outer{
	z-index: 5;
	margin-left: 47.5%;
    margin-top: 25%;
	width: 5%;
	position: absolute;
}
#inner {
	z-index: 5;
	width: 100%;
	height: 100%;
	padding-bottom: 100%;
    border-radius: 50%;
    background-color: blue;
   
}
#power {
	z-index: 5;
	position: absolute;
	width: 100%;
	height: 100%;
	
}
<html>
<head>
	<link rel="stylesheet" type="text/css" href="design.css">
	<title></title>
</head>
<body>
<div id="container">
	<div id="outer">
	<div id="inner" >
	<a href="javascript:slide()">
		<img id="power" src="off.png">
 	</a>
	</div>
	</div>
	<div id="left"></div>
	<div id="right"></div>
</div>
</body>
</html>

附带说明一下,在代码片段中,您的JavaScript不需要位于script标记内部,只要它位于JavaScript部分即可。

试试这个:

document.getElementById("left").style.left = "-100px";