繁体   English   中英

如何使用 javascript 居中和放大文本?

[英]How to center and enlarge text using javascript?

我想用下面的代码做的随机文本引用替换 div 内容(我正在编写 Chrome web 扩展名); 但我不知道如何使用 javascript 来操作文本,以便我可以居中、放大文本、将文本向下移动几行等。因为我无法访问原始 HTML(这是为了Chrome 扩展程序),我需要使用 javascript 来完成此操作。 这可能吗?

const quotes = [
'Quotation 0.',
'Quotation 1.',
'Quotation 2.'
];
index = Math.floor(Math.random() * quotes.length);
document.getElementById('pageContent').outerHTML = quotes[index];

js不会导致文本的渲染,浏览器会解释html和css来渲染文本。 您可以使用 js 注入 html 和 css 以获得您想要的效果。 如果您不能直接编辑 html 或 css 文档,您可以使用内联样式来创建视觉效果,但是 chrome 扩展确实可以注入 css 以及

如何修改您提供的代码:

const quotes = [
  'Quotation 0.',
  'Quotation 1.',
  'Quotation 2.'
];
const index = Math.floor(Math.random() * quotes.length);
const h2 = document.createElement("h2");
h2.style.cssText = `
  text-align: center;
  font-size: 3rem;
  margin: 1rem;
`;
h2.innerText = quotes[index];

document.getElementById('pageContent').appendChild(h2);

这实际上是一个级联样式表 (CSS) 问题。

您可以使用 CSS 的

text-align: "center"
font-size: "130%"

我还建议您查看字体大小可以具有的其他设置(相对于百分比)。 如果您可以在 CSS 样式表上应用这些 styles,那就更好了。 但是如果你想在 JavaScript 做,你可以做

myElement.style.textAlign = "center";
myElement.style.fontSize = "130%"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM