gpt4 book ai didi

javascript - 样式化 JS 生成的代码

转载 作者:行者123 更新时间:2023-11-28 09:02:59 24 4
gpt4 key购买 nike

我正在使用“查找和替换”类型的 javascript 函数,并将 HTML 中的所有反引号替换为 <code>标签,以及所有带有 </code> 的井号标签。出于某种原因,我的样式无法正常工作,除非我使用 .css() 将它们编码到 JS 文件中。方法。

理想情况下,组合应该将反引号和井号之间的代码输出为被阻止的 <code>内容,(<code> 标签由 JavaScript 生成)具有柔和的灰色背景。但是,由于某种原因,样式没有显示出来。

如果有人能提供帮助,我将不胜感激。

这是我的 html 文件 test.html :

<!DOCTYPE html>
<head>
<title>Script Test</title>
<script src="http://code.jquery.com/jquery-2.1.1.js"></script>
<link rel="stylesheet" href="styles/code/style.css" type="text/css">
</head>
<body>
<p>This is some code:
`var p = 10; #
`var a = 5; #
`var x; #
`x = a * p; #
`console.log(x); #
All I want is for this to work!
</p>
<script src="codeStyle.js"></script>
</body>

我的 CSS 文件(从 SASS 编译)style.css :

body {
color: #121212;
font-family: 'Helvetica Neue', serif;
font-weight: 300;
letter-spacing: .25px; }

body div.container {
padding: 10px; }

body div.container code.styled {
font-family: arial, serif;
background-color: #f9f9f9; /* soft gray bg color */
display: block; /* block display style */
margin: 2px 0 2px 2.5%;
padding: 3px;
width: auto;
background-color: #fafafa;
border: 1px solid #f5f5f5; }

/*# sourceMappingURL=style.css.map */

还有我的js文件codeStyle.js :

$('p').each(function() {
var text = $(this).html(); // Grab HTML from each <p>
text = text.replace(/`/gi,"<code class='styled'>"); // Replaces every ` with <code>
text = text.replace(/#/gi,"</code>"); // Replaces every # with </code>
$(this).html(text); // Set <p> html as replaced code
});

最佳答案

将 Partick 的回答放在上面:您的 CSS 正试图定位一个不存在的元素。

问题出在这段 CSS 中:

 body div.container code.styled { }

没有匹配此选择器的内容,因为没有<div class="container">

要解决这个问题,您可以从 CSS 中删除有问题的选择器:

body code.styled {}

或将所需的选择器添加到您的 HTML 中:

<div class="container">
<p>Some text <code class="styled">some code</code>.</p>
</div>

这是一个 Fiddle 它的工作。

关于javascript - 样式化 JS 生成的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835710/

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