简体   繁体   English

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

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

I want to replace div content with a random text quotation (I am coding a Chrome web extension) which the code below does;我想用下面的代码做的随机文本引用替换 div 内容(我正在编写 Chrome web 扩展名); but I don't know how to use javascript to manipulate the text so that I can center it, enlarge the text, bump the text down a few lines, etc. As I do not have access to the original HTML (this is for a Chrome Extension), I need to accomplish this with javascript.但我不知道如何使用 javascript 来操作文本,以便我可以居中、放大文本、将文本向下移动几行等。因为我无法访问原始 HTML(这是为了Chrome 扩展程序),我需要使用 javascript 来完成此操作。 Is this possible?这可能吗?

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

js does not cause the rendering of text, the browser interprets the html and css to render the text. js不会导致文本的渲染,浏览器会解释html和css来渲染文本。 You can use js to inject html and css for you desired effect.您可以使用 js 注入 html 和 css 以获得您想要的效果。 If you can not directly edit the html or css document, you can use inline stylings to create visual effects, however chrome extension do have the ability to inject css as well as js.如果您不能直接编辑 html 或 css 文档,您可以使用内联样式来创建视觉效果,但是 chrome 扩展确实可以注入 css 以及

How about something like modification to the code you provided:如何修改您提供的代码:

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);

This is really a Cascading Style Sheets (CSS) question.这实际上是一个级联样式表 (CSS) 问题。

You can use CSS's您可以使用 CSS 的

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

I also advise you to look into what other settings font-size can have (vis-a-vis percentage).我还建议您查看字体大小可以具有的其他设置(相对于百分比)。 It is better if you can apply these styles on a CSS stylesheet.如果您可以在 CSS 样式表上应用这些 styles,那就更好了。 But if you want to do it in JavaScript, you can do但是如果你想在 JavaScript 做,你可以做

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

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

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