字体、字体大小和颜色更改 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28163255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:31:00  来源:igfitidea点击:

font,font size, and color change javascript

javascripthtmlcssfonts

提问by Piratica

I am trying to make this code change the pre-written text font, font size, and color with an onclick button but am unable to make it work this is what i have so far and im stuck. anyone have any ideas?

我正在尝试使用 onclick 按钮使此代码更改预先编写的文本字体、字体大小和颜色,但无法使其正常工作,这是我迄今为止所做的,并且我卡住了。有人有想法么?

<html>
  <head> 
      <meta charset=utf-8 /> 
      <title>Change Paragraph Text</title> 
  </head>  
  <body> 
      <p id ='text'>I am going to change this text, I hope.</p>  
      <div>
        <button id="jschange" onclick="DoAll">Style</button> 
      </div>
      <script type="text/javascript">
         var style = 'text';
         function DoAll() {
            One(document.write.style.big());
            Two(document.write.style.fontsize(7));
            Three(document.write.style.fontcolor("red"));
         }
      </script>
  </body> 
</html>

回答by Elegant.Scripting

Try this, it's a much simpler approach and won't make anyone's eyes bleed:

试试这个,这是一个更简单的方法,不会让任何人的眼睛流血:

<button onclick="restyle()">Click me to see some results</button>

<p id="changeable">Text that will change.</p>

<script>
   function restyle() {
      var element = document.getElementById("changeable");
      element.style.fontsize(7);
      element.style.fontcolor("red");
      element.innerHTML = "changed text";
   }
</script>

I'm still learning Javascript too, so if there are any experts out there I'd love to hear what they think! :)

我也在学习 Javascript,所以如果有任何专家在那里,我很想听听他们的想法!:)

回答by Norguard

<!doctype html>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <p id="style-target">This is the element which will change.</p>
    <button id="change-styles">Change Styles</button>
    <script>

      window.onload = function () {
        var changeStyles = query("#change-styles");
        var target = query("#style-target");

        changeStyles.onclick = function () {
          style(target, "fontSize", "18px");
          style(target, "color", "blue");
          style(target, "fontWeight", "bold");
        };
      };

      function style (el, property, value) {
        el.style[property] = value;
      }

      function query (selector) {
        return document.querySelector(selector);
      }
    </script>
  </body>
</html>

Have a look;

看一看;

I've taken the liberty of adding the rest of the "required" HTML bits and pieces, there (especially the DOCTYPE). You don't need to know what it's there for, right now, but it will solve a lot of problems in the future, if you always include it at the top of every HTML page you write, if you intend real people to use that page (basically, it makes Internet Explorer < IE10 suck less).

我冒昧地在那里添加了其余的“必需”HTML 零碎部分(尤其是 DOCTYPE)。你现在不需要知道它的用途,但它会在未来解决很多问题,如果你总是将它包含在你编写的每个 HTML 页面的顶部,如果你打算让真人使用它页面(基本上,它使 Internet Explorer < IE10 变得更少)。

I've broken this down into bits that are a little more sensible, in terms of real-world JavaScript.

就现实世界的 JavaScript 而言,我已将其分解为更合理的部分。

In most programming languages, you want to break your code down into smaller bits, to make it easier to read and work with.
JavaScript isn't really much different.

在大多数编程语言中,您希望将代码分解成更小的部分,以使其更易于阅读和使用。
JavaScript 并没有太大的不同。

I have broken apart apart the act of setting the style, into its own helper function

我已经将设置样式的行为分解为它自己的辅助函数

el.style.color = "purple"; // takes `el` and makes an el{color:purple} rule

The catch here is that any CSS "style" that has a hyphen ("font-size", "background-color") needs to use camelCase, when setting the value in JavaScript.

这里的问题是,在 JavaScript 中设置值时,任何带有连字符(“字体大小”、“背景颜色”)的 CSS“样式”都需要使用驼峰式大小写。

el.style.backgroundColor = "black";

I've created a helper function called style, which I then refer to inside of my window.onloadcode.

我创建了一个名为 的辅助函数style,然后在我的window.onload代码中引用它。

In this particular case, I'm not saving a lot, in terms of what I'm typing (in fact, I'm typing more), but what it would be saving me, in a more complex case, is the chance of missing something, in repeating myself, or in copy/pasting...

在这种特殊情况下,就我输入的内容而言,我并没有节省很多(实际上,我输入的内容更多),但是在更复杂的情况下,它可以节省我的钱遗漏了一些东西,在重复自己,或在复制/粘贴...

So by calling style(el, "fontWeight", "bold");I don't have to remember how to set the style for old-browsers, versus new browsers, versus styles that have been set using JS earlier on, versus those that haven't (a topic for people concerned with professional websites that have to work on ancient browsers).

因此,通过调用,style(el, "fontWeight", "bold");我不必记住如何为旧浏览器设置样式,与新浏览器相比,与之前使用 JS 设置的样式相比,与未设置的样式相比(这是关注专业网站的人的主题)必须在古代浏览器上工作)。

If you look inside of the definition for stylethat I wrote, you'll see that I'm calling el.style[property]; normally, when we know the name of the thing we're looking for, on an object, we use a dot to separate them person.name; //"Bob".
In circumstances where we might want to look for different properties, we use [<property-name>]to separate them.

如果您查看style我编写的定义的内部,您会看到我正在调用el.style[property]; 通常,当我们知道要查找的事物的名称时,在一个对象上,我们会使用一个点来分隔它们person.name; //"Bob"
在我们可能想要寻找不同属性的情况下,我们使用[<property-name>]将它们分开。

var property = "age"; person[property]; // 32

var 属性 = "年龄"; 人[财产]; // 32

Next, I am using document.querySelector( selector );to find the elements that I want, by passing it a CSS-style selector.

接下来,我通过document.querySelector( selector );向它传递一个 CSS 样式选择器来查找我想要的元素。

document.querySelectorworks on practically all browsers made in the past 6 years.

document.querySelector几乎适用于过去 6 年制造的所有浏览器。

I'm grabbing the element I want to change the styles of, and I'm grabbing the element I'm listening to (waiting for a user to click).

我正在抓取我想要更改其样式的元素,并且我正在抓取我正在收听的元素(等待用户单击)。

Then I'm setting the onclickof the button to a function which will fire off a bunch of changes that I specify.
In this case, the onclick will change some styles.

然后我onclick将按钮的设置为一个函数,该函数将触发我指定的一系列更改。
在这种情况下,onclick 会改变一些样式。

You don't typically want to use onclickor similar properties; normally, you want to use a process called event-registrationor "listening", but that goes a little too far, for such a simple example.

您通常不想使用onclick或类似的属性;通常,您想使用称为event-registration或“侦听”的过程,但对于这样一个简单的示例,这有点过头了。

For now, grab the elements, separate your "how you do it" implementation details from "when 'X' do 'Y'" runtime details, and watch magic happen.

现在,抓住元素,将“你如何做”的实现细节与“当‘X’做‘Y’”的运行细节分开,然后观察奇迹的发生。

Funny enough, this isn't much more code than the jQuery suggestion provided in another answer...

有趣的是,这并不比另一个答案中提供的 jQuery 建议多多少代码......

...but that's a whole, gigantic library that you'd have to load (if you were even allowed), just to select a thing and change its styles.
Also, by using the "jQuery solution" to common problems, you frequently learn bad habits, or alternatively, don't learn good habits which you would need to learn, had you not had the quick and easy solution in front of you.
jQuery, as used by most people, is particularly bad about reference-caching (or a lack thereof). If widely used jQuery patterns are employed on a production website, without thought put into them (especially if you're not using jQuery, but some other library like it), you can murder your website's performance.

...但这是一个完整的、巨大的库,您必须加载(如果您被允许),只需选择一个内容并更改其样式即可。
此外,通过使用“jQuery 解决方案”解决常见问题,您经常会学习坏习惯,或者,如果您没有摆在面前的快速简便的解决方案,则不会学习您需要学习的好习惯。
大多数人使用的 jQuery 在引用缓存方面尤其糟糕(或缺乏引用缓存)。如果在生产网站上使用了广泛使用的 jQuery 模式,而没有考虑到它们(特别是如果您不使用 jQuery,而是使用其他一些类似的库),您可能会破坏网站的性能。

回答by Alex Vazhev

I think you should do it like this:

我认为你应该这样做:

<html>
  <head>
     <script  src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  </head>
  <body>
     <p id ='text'>I am going to change this text, I hope.</p>  
     <div>
       <button id="jschange" onclick="DoAll()">Style</button> 
     </div>

    <script>
      function DoAll() {
        $('#text').css('font-size', '7').css('color', 'red');
      }
    </script>
  </body>
</html>

回答by OnlyMAJ

Try this instead that js code:

试试这个,而不是 js 代码:

var sstyle = 'text';
function DoAll() {
   var elem = document.getEelementById(sstyle);
   elem.style.fontSize = "7px";
   elem.style.color= "red";
}

回答by Neminath

You can try this:

你可以试试这个:

<!DOCTYPE html>
<html>
  <body>

    <p>Click the button to display a string in a specified size.</p>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>

    <script>
        function myFunction() {
            var str = "Hello World!";
            var result = str.fontsize(7);
            document.getElementById("demo").innerHTML = result;
        }
    </script>
  </body>
</html>