gpt4 book ai didi

javascript - HTML 和 JS 冲突元素 (MouseOver)

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:18 25 4
gpt4 key购买 nike

我试图在我的布局中添加一个元素,以便在鼠标悬停时更改文本和背景颜色,然后在鼠标悬停时恢复到它们的原始状态。问题是 JS 似乎无法识别我的 CSS 的本质。

元素 (#sidebar) 有这些 CSS 代码片段(侧边栏本身的代码不相关):

#sidebar ul {
list-style-type: none;
}

#sidebar li {
width:100px;
border-radius: 25px;
text-align: center;
background-color: #AFCEEA;
border: 5px solid #195A94;
font-weight: bold;
line-height: 50px;
margin-top: 10px;
margin-left: 5px;
}

它看起来像这样,在 OnMouseOver 之前:

enter image description here

这是我用来尝试 onMouseOver 的 JS:

<script type="text/javascript">
function changeColor(myColor) {
var sidebar = document.getElementById('sidebar li');
sidebar.style.fontcolor = "#6588C7";
sidebar.style.backgroundColor = "#6588C7";
}
</script>

在 div 中使用此实现:

<div id ="sidebar li">
<ul><li onmouseover="changeColor('new color')"><p class="class1">writing<p></li></ul>
</div>

但它对我的侧边栏执行此操作:

enter image description here

我怎样才能让颜色留在小盒子里?

最佳答案

您可以使用 :hover 代替 onmouseover 来真正简化您的代码。

我正在使用 flexbox li 使中心对齐变得容易。您不再需要抑制 list-style,因为列表项不再显示为列表项。

对于段落,您可能不再需要 class1。我只是把它们放在里面。

function changeText(myText) {
//find variable on page called 'myContent' and give it var name display
var display = document.getElementById('content');
display.innerHTML = "";
display.innerHTML = "New content.";
}
#sidebar li {
width: 100px;
height: 100px;
border-radius: 25px;
background-color: #AFCEEA;
border: 5px solid #195A94;
font-weight: bold;
display: flex;
align-items: center; /* Vertical alignment */
justify-content: center; /* Horizontal alignment */
}

#sidebar li:hover {
background-color: red;
}
/* Apply top margin to all list elements except for the first one */
#sidebar li:not(:first-child) {
margin-top: 10px;
}

#content {
border-radius: 25px;
width: 750px;
height: 500px;
margin-top: 50px;
margin-left: 300px;
background-color: azure;
padding: 50px;
}
<div id="sidebar">
<ul>
<li>
<p class="class1">writing<p>
</li>
<li>
<p class="class1">games/art<p>
</li>
<li>
<p class="class1">music<p>
</li>
</ul>
</div>

<div id="content" onclick="changeText()"> <p>Content here.</p> </div>

关于javascript - HTML 和 JS 冲突元素 (MouseOver),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52733291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com