我有一个程序,其中显示了一系列标签,每次单击它们时,它们都会出现在一个 div ( <div id = "div1"> </ div>
) 中,要删除标签,您必须返回单击但这次是在标签上出现在 div1 中。
我现在正在尝试的是,每次我点击 div1 外部的标签时,它们都会变成蓝色,如果我从 div1 中删除它们,它们会恢复到原来的颜色。
你能帮帮我吗?我可以用 html + css 做吗?或者我需要 js?
这是我的 JS:
var ar = new Array();
function myFunction(tagName, tagId) {
if (!document.getElementById(tagName)) {
document.getElementById("div1").innerHTML +=
'<label class="tags" id="' + tagName + '" onclick="rem(\'' + tagName + '\', \'' + tagId+ '\')">' + tagName + ', </label>';
ar.push(tagId);
document.getElementById("hiddenfield").value = ar;
}
}
function rem(tagName, tagId) {
document.getElementById(tagName).remove();
ar.splice(ar.indexOf(tagId), 1);
document.getElementById("hiddenfield").value = ar;
}
这是我的 PHP:
<p>
Introduce tags:
</p>
<div id="div1">
</div>
<h3>
<?php
while($row = $result->fetch_assoc()) {
echo "<label><a class=\"trigger blue lighten-4\" data-toggle=\"modal\" data-target=\"#conditionModal\" onclick=\"myFunction('" . $row["tag_name"] ."', '" . $row["tag_id"] ."')\">" . $row["tag_name"] ." </a></label>";
}
?>
</h3>
这是我的 CSS:
.trigger {
padding: 1px 10px;
font-size: 20px;
font-weight: 400;
border-radius: 10px;
background-color: aliceblue;
color: #212121;
display: inline-block;
margin: 2px 5px;
cursor:pointer;
}
a:hover {
color: black;
background-color: red;/* #e6e6e6 */
}
/* selected link */
a:active {
color: white;
}
.tags {
font-family: Arial, Helvetica, sans-serif;
cursor:pointer;
padding: 1px 10px;
font-size: 15px;
font-weight: 400;
border-radius: 10px;
background-color: aliceblue;
color: #212121;
display: inline-block;
margin: 2px 5px;
}
.tags:hover {
color: red;
}
我想要的是这样的:
http://jsfiddle.net/Shef/L6VqK/
但不是点击同一个链接,链接在 Div1 中
最佳答案
这些是基础知识。只有两个包含标签的元素。 (我在这里使用列表,因为在列出多个元素时使用列表是有意义的。)然后让颜色由它们所属的列表确定,而不是让元素本身的颜色。
从一个列表切换到另一个列表就像将目标附加到新列表一样简单。
const tags = [ ...document.querySelectorAll( '.tag' )];
const input = document.querySelector( '#tags_input' );
const output = document.querySelector( '#tags_output' );
const move = event => {
const list = event.target.parentNode.parentNode;
if ( list.id === 'tags_input' ) output.appendChild( event.target.parentNode );
else if ( list.id === 'tags_output' ) input.appendChild( event.target.parentNode );
};
tags.forEach( tag => tag.addEventListener( 'click', move ));
#tags_input .tag {
background-color: lightblue;
}
#tags_output .tag {
background-color: grey;
}
<ul id="tags_input">
<li class="tag"><a href="#">First tag</a></li>
<li class="tag"><a href="#">Second tag</a></li>
<li class="tag"><a href="#">Third tag</a></li>
<li class="tag"><a href="#">Fourth tag</a></li>
<li class="tag"><a href="#">Fifth tag</a></li>
<li class="tag"><a href="#">Sixth tag</a></li>
<li class="tag"><a href="#">Seventh tag</a></li>
</ul>
<ul id="tags_output"></ul>
请记住,这与基本链接功能非常相似,已点击的链接使用 :visited 颜色,这完全可以在 CSS 中完成(通过使用 a:visited、a:hover、a:active 等) .
它只是移动元素并将链接颜色重置为原始颜色,就好像链接还没有被点击一样,这在 CSS 中无法完全完成。
关于javascript - 单击时切换颜色链接颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55689863/