【发布时间】:2021-10-13 11:26:58
【问题描述】:
我正在尝试使用 Svelte 对方程式进行一些条件样式和突出显示。虽然我已经成功地将全局静态样式应用于类,但我不知道在事件发生时如何执行此操作(例如悬停在类的一个实例上)。
我是否需要创建一个存储值(即当类悬停时设置为 true 的一些布尔值)才能使用条件样式?或者我可以像下面的示例中那样编写一个针对该类的所有实例的函数吗?我有点不清楚为什么在样式中定位一个类需要:global(classname) 格式。
App.svelte
<script>
// import Component
import Katex from "./Katex.svelte"
// math equations
const math1 = "a\\htmlClass{test}{x}^2+bx+c=0";
const math2 = "x=-\\frac{-b\\pm\\sqrt{b^2-4ac}}{2a}";
const math3 = "V=\\frac{1}{3}\\pi r^2 h";
// set up array and index for reactivity and initialize
const mathArray = [math1, math2, math3];
let index = 0;
$: math = mathArray[index];
// changeMath function for button click
function changeMath() {
// increase index
index = (index+1)%3;
}
function hoverByClass(classname,colorover,colorout="transparent")
{
var elms=document.getElementsByClassName(classname);
console.log(elms);
for(var i=0;i<elms.length;i++)
{
elms[i].onmouseover = function()
{
for(var k=0;k<elms.length;k++)
{
elms[k].style.backgroundColor=colorover;
}
};
elms[i].onmouseout = function()
{
for(var k=0;k<elms.length;k++)
{
elms[k].style.backgroundColor=colorout;
}
};
}
}
hoverByClass("test","pink");
</script>
<h1>KaTeX svelte component demo</h1>
<h2>Inline math</h2>
Our math equation: <Katex {math}/> and it is inline.
<h2>Displayed math</h2>
Our math equation: <Katex {math} displayMode/> and it is displayed.
<h2>Reactivity</h2>
<button on:click={changeMath}>
Displaying equation {index}
</button>
<h2>Static math expression within HTML</h2>
<Katex math={"V=\\pi\\textrm{ m}^3"}/>
<style>
:global(.test) {
color: red
}
</style>
Katex.svelte
<script>
import katex from "katex";
export let math;
export let displayMode = false;
const options = {
displayMode: displayMode,
throwOnError: false,
trust: true
}
$: katexString = katex.renderToString(math, options);
</script>
<svelte:head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css" integrity="sha384-AfEj0r4/OFrOo5t7NnNe46zW/tFgW6x/bCJG8FqQCEo3+Aro6EYUG4+cU+KJWu/X" crossorigin="anonymous">
</svelte:head>
{@html katexString}
【问题讨论】:
-
全局是必需的,因为该类不是使用 Svelte 有条件地添加的,并且在您的标记中不存在。但是,是否有某些原因您不只使用 CSS? “当类的一个实例悬停时”在 CSS 中看起来像这样:
.className:hover {styling}并且当该类悬停时将一直工作,不需要 JS。 -
感谢您的回复。我试图突出显示同一类的多个实例(即,如果用户将鼠标悬停在一个“x”上,则“x”的所有实例都应该应用条件样式,而不仅仅是悬停的那个)。
-
您也可以定位兄弟姐妹。
.className:hover ~ .className, .className:hover {styling}
标签: javascript html css svelte svelte-component