Tengo un archivo html estático que contiene principalmente texto. Muchos fragmentos de texto se resaltan con la etiqueta <mark> . Me gustaría agregar un botón que alterne el peso del texto de los fragmentos de texto marcados entre negrita y normal. El efecto buscado es encender/apagar el resaltado.
¿Hay alguna forma mágica de hacerlo cambiando directamente el estilo de la clase mark css?
Ejemplo:
... This is an <mark>important text snippet</mark> ...mark { text-weight: bold; }mark { text-weight: normal; }La razón por la que quiero hacer esto es permitir que el usuario decida si quiere ver el texto resaltado o no. Sé que puedo cambiar el estilo de cada fragmento de texto marcado, pero me pregunto si hay una forma más directa.
Una forma más directa sería agregar una clase a un elemento principal . Luego, en CSS, puede seleccionar todos los elementos de mark secundarias. Este método le evita iterar sobre cada elemento de marca en su página en JS. Puede agregar esta clase en un div contenedor o incluso en el elemento html raíz si lo desea.
classList.toggle es compatible con todos los principales navegadores: https://caniuse.com/?search=classlist.toggle
function toggleMarkup() {
document.querySelector("#content").classList.toggle("markup-shown");
}
p.markup-shown mark {
font-weight: bold;
}
<p id="content">
Hello! This is some <mark>marked up</mark> text! And this is some more <mark>marked</mark> text.
</p>
<button onclick="toggleMarkup()">
Click me to toggle markup.
</button>
https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model https://stackoverflow.com/a/55468693/9627251
También puede obtener y modificar clases CSS existentes directamente desde JS:
const rules = document.styleSheets.map(sheet => sheet.cssRules);
const rule = rules.find(r => r.selectorText == 'mark');
rule.style.fontWeight = 'bold'; // or normal, in your toggle function logic
Tenga en cuenta que ya debería tener una regla CSS como:
mark { font-weight: normal; }
Consulte todos sus elementos de mark , luego cambie una clase de resaltado para afectar su estilo de peso de fuente. Obtenga los padres de los elementos de marca usando '.closest()' y agregue un botón a cada elemento padre.
const marks = document.querySelectorAll('mark')
// use event target to get the parent element and subsequent
// mark element and toggle a class of normal font weight
function toggleHighlight(e) {
e.target.closest('li').querySelectorAll('mark').forEach( el => {
el.classList.toggle('normal')
})
}
marks.forEach(mark => {
// create the button
const button = document.createElement('button')
// add text for the button
button.textContent = 'Toggle Highlight'
// get the parent element your mark is living within and append the button to it
// make sure it only gets one button in case there are more than one mark element
!mark.parentNode.innerHTML.includes('button') ? mark.parentNode.appendChild(button) : null
// event listener for when the button is pressed
button.addEventListener('click', toggleHighlight)
})
mark {
font-weight: bold;
}
.normal {
font-weight: normal;
}
li {
clear: left;
}
button {
float: right;
}
<ul>
<li>This is not important text</li><hr>
<li><mark>This text here important text.</mark> But this is not. <mark>We have more important text here as well.</mark> Arcu cursus euismod quis viverra nibh cras pulvinar mattis. Tristique et egestas quis ipsum suspendisse ultrices gravida dictum. Ac turpis egestas integer eget. </li><hr>
<li>This is text not important text. <mark>But this is</mark></li><hr>
<li><mark>This text here important text.</mark> But this is not</li><hr>
</ul>
¿Qué pasa con algo como esto?
<html>
<head>
<style>
mark {
font-weight: bold;
background: none;
}
</style>
</head>
<body>
This is an <mark>important text snippet</mark> and so <mark>is this</mark>.
<button onclick = "changeMark()">Change Mark Style</button>
<script>
function changeMark() {
document.querySelectorAll("mark").forEach(e => e.style.fontWeight = "normal");
}
</script>
</body>
</html>