简体   繁体   English

将CSS添加到文档加载后创建的元素中

[英]Adding CSS to an element created after document load

I recently asked a question about how to make an h1 with javascript and determine what the innerHTML will be. 我最近问了一个有关如何使用javascript制作h1并确定innerHTML将是什么的问题。 I tried every answer and none of them worked so I'm posting my entire code in case I have something in there that requires a different solution. 我尝试了所有答案,但没有一个起作用,因此我发布了整个代码,以防万一我有需要其他解决方案的内容。

HTML 的HTML

<!DOCTYPE html>
<html>

  <head>
    <link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Arimo:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css">
    <script src="js/time.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  </head>

  <body>
    <div class="wrap">
      <div id="time">
      </div>
      <div class="nav">
        <div class="container">
          <ul class="pull-left">
            <li><a href="#">Home</a></li>
            <li><a href="#">Gallery</a></li>
          </ul>
          <ul class="pull-right">
            <li><a href="#">About Me</a></li>
            <li><a href="#">Contact Me</a></li>
            <li><a href="#">Help</a></li>
          </ul>
        </div>
      </div>

      <div class="jumbotron">

        <div class="container">
          <h1>Forum Signatures</h1>
          <p>A hobbyist art style wherein the artist uses various methods to create appealing effects around a render cut from a previously existing image.</p>
          <!--- <a href="#">Learn More</a> --->
        </div>

      </div>
      <div class="neighborhood-guides">
        <div class="container">
          <h2>Favorite Pieces</h2>
          <!---<p>Not sure where to stay? We've created neighborhood guides for cities all around the world.</p>--->
          <div class="row">
            <div class="col-md-2">
              <div class="thumbnail">
                <a class="images" href="http://shniper1337.deviantart.com/art/The-Colors-438254150">
                  <img class="colors" src="images/colors.png"></a>
              </div>

            </div>

            <div class="col-md-2">
              <div class="thumbnail">
                <a class="images" href="http://shniper1337.deviantart.com/art/Schitz-443257857">
                  <img class="schitz" src="images/schitz.png"></a>
              </div>
              <div class="thumbnail">
                <a class="images" href="http://shniper1337.deviantart.com/art/Arcade-Sona-443074789">
                  <img class="sona" src="images/sona.png"></a>
              </div>
            </div>
            <div class="col-md-2">
              <div class="thumbnail">
                <a class="images" href="http://shniper1337.deviantart.com/art/Mass-Effect-Signature-443034977">
                  <img class="mass" src="images/mass_effect.png"></a>
              </div>
              <div class="thumbnail">
                <a class="images" href="http://shniper1337.deviantart.com/art/Test-your-Luck-449429967">
                  <img class="tf" src="images/tf.png"></a>
              </div>
            </div>
            <div class="col-md-2">
              <div class="thumbnail">
                <a class="images" href="http://shniper1337.deviantart.com/art/Super-Serial-442310653">
                  <img class="serial" src="images/serial.png"></a>
              </div>
              <div class="thumbnail">
                <a class="images" href="http://shniper1337.deviantart.com/art/Teemo-438254430">
                  <img class="teemo" src="images/teemo.png"></a>
              </div>
            </div>
            <div class="col-md-2">
              <div class="thumbnail">
                <a class="images" href="http://shniper1337.deviantart.com/art/Death-From-Above-448908808">
                  <img class="assassin" src="images/assassin.png"></a>
              </div>
              <div class="thumbnail">
                <a class="images" href="http://krucifiks.deviantart.com/art/Abstract-Tag-345903925">
                  <img class="abstract" src="images/abstract.png"></a>
              </div>
            </div>
            <div class="col-md-2">
              <div class="thumbnail">
                <a class="images" href="http://shniper1337.deviantart.com/art/Normal-is-just-too-boring-452311932">
                  <img class="normal" src="images/normal.png"></a>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="learn-more">
        <h2>Other Work</h2>
        <div class="container">
          <div class="row">
            <div class="col-md-4">
              <a href="#"><h3>Web Design</h3></a>
              <p>Extensive experience with HTML5 and CSS3. Multiple websites created, unique perspective of a designer and IT major combined.</p>
            </div>
            <div class="col-md-4">
              <a href="#"><h3>Graphic Design</h3></a>
              <p>Strong background in Photoshop as well as professional experience in Illustrator and InDesign.</p>

            </div>
            <div class="col-md-4">
              <a href="#"><h3>Software Engineering</h3></a>
              <p>Information Technology student with a passion for logic and programming. Experience with Javascript, some JQuery and some Python.</p>

            </div>
          </div>

        </div>
      </div>
    </div>

    <script>
      $(function() {

        $('#time').animate({
          right: '0%'
        }, 2000).delay(1500).animate({
          right: '100%'
        }, 2000);
      });

    </script>
    <noscript><link href="main.css" rel="stylesheet"></noscript>
  </body>

</html>

CSS 的CSS

body {
    background-color: #495987;
}

.wrap {
  background-color: #000000;
}

#time {
  width: 100%;
  height: 50px;
  right: -100%;
  position: absolute;
  top: 50px;

}

#time h1: {
  color: #FFAB23;
  font-size: 38px;
  font-family: 'Arimo', sans-serif;
  font-weight: 700;
  text-align: center;
  letter-spacing: 5px;
  font-style: italic;
  margin-top: 0px;
  line-height: 50px;
  text-shadow: 3px 3px 5px #111;
}

a {
  text-decoration: none;
}

.nav {
  background-color: #495987;
  height: 50px;
  width: 100%;
}

.nav a {
  color: #E16024;
  font-size: 11px;
  font-weight: bold;
  padding: 14px 10px;
  text-transform: uppercase;
  text-decoration: none;
}

.nav a:hover {
  font-size: 14px;
  color: #FFAB23;
}

.nav li {
  display: inline;
}

.jumbotron {
  background-image: url('images/design.png');
  height: 500px;
  background-repeat: no-repeat;
  background-size: cover;
}

.jumbotron .container {
  position: relative;
  top: 100px;
}

.jumbotron h1 {
  color: #cac9b9;
  font-size: 48px;
  font-family: 'Arimo', sans-serif;
  font-weight: 700;
}

.jumbotron p {
  font-size: 16px;
  color: #222222;
  max-width: 430px;
  padding-top: 10px;
}

.learn-more {
  background-color: #495987;
}

.learn-more h3 {
  font-family: 'Arimo', sans-serif;
  font-size: 18px;
  color: #E16024;
  text-align: center;
}

.learn-more h2 {
  font-family: 'Arimo 700', sans-serif;
  text-align: center;
  color: #F3B600;
  font-weight: bold;
  text-shadow: 2px 2px 3px #111;
}

.learn-more h3:hover {
  font-size: 21px;
  color: #FFAB23;
}

.learn-more p {
  text-align: center;
  color: #BFD3EE;
}

.learn-more a {
  text-decoration: none;
}

.neighborhood-guides {
  background-color: #495987;
}

.neighborhood-guides h2 {
  color: #F3B600;
  text-align: center;
  font-weight: bold;
  text-shadow: 2px 2px 3px #111;
}

.neighborhood-guides p {
  font-size: 15px;
  margin-bottom: 13px;
}

.normal {
  width: 150px;
}

.colors {
  width: 130px;
}

.thumbnail {
  transition: .4s linear;
  transition: opacity .3;
  box-shadow: 0px 0px 10px #111;
}

.thumbnail:hover {
  transform: scale(2.2);
  -webkit-transform: scale(2.2);
  z-index: 1;
  box-shadow: 3px 3px 5px #111;;

}

.container:hover .thumbnail img:not(:hover) {
  opacity: 0.3;
}

JS JS

function getStylesheet() {
      var currentTime = new Date().getHours();
      if (0 <= currentTime&&currentTime < 5) {
       document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
       var h1 = document.createElement("h1");
       h1.innerHTML = "Good Morning!";

       document.getElementById("time").appendChild(h1);
      }
      if (5 <= currentTime&&currentTime < 12) {
       document.write("<link rel='stylesheet' href='morning.css' type='text/css'>");
       var h1 = document.createElement("h1");
       h1.innerHTML = "Good Morning!";

       document.getElementById("time").appendChild(h1);
      }
      if (12 <= currentTime&&currentTime < 17) {
       document.write("<link rel='stylesheet' href='day.css' type='text/css'>");
       var h1 = document.createElement("h1");
        h1.id= "timeh1";
        document.getElementById("time").appendChild(h1);
        document.getElementById("timeh1").innerHTML = "Good Afternoon!";

       document.getElementById("time").appendChild(h1);
      }
      if (17 <= currentTime&&currentTime < 22) {
       document.write("<link rel='stylesheet' href='evening.css' type='text/css'>");
       var h1 = document.createElement("h1");
       h1.innerHTML = "Good Evening!";

       document.getElementById("time").appendChild(h1);
      }
      if (22 <= currentTime&&currentTime <= 24) {
       document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
       var h1 = document.createElement("h1");
       h1.innerHTML = "Good Evening!";

       document.getElementById("time").appendChild(h1);
      }
}

getStylesheet();

So I'm trying to create an h1 in the #time id which starts off of the screen and animates to the middle and then goes back off using JQuery. 因此,我尝试在#time id中创建一个h1,该h1从屏幕开始并动画到中间,然后使用JQuery返回。 Even when I comment out all css and the JQuery the h1 does not appear on the screen. 即使当我注释掉所有CSS和JQuery时,h1也不会出现在屏幕上。

Please Help. 请帮忙。

For one, looks like when you create the h1 it should be like: 首先,当您创建h1时,它应类似于:

document.createElement("H1");

note the capital H. Refer here: createElement 注意大写字母 H。请参阅此处: createElement

Next time, please set up an example on JSFiddle so it would be easier for others to tinker with your code example. 下次,请在JSFiddle上建立一个示例,这样其他人可以更轻松地修改您的代码示例。 It also helps us help you if the title depicts the actual problem you're describing. 如果标题描述的是您要描述的实际问题,它也可以帮助我们。

Solving the issue mentioned in your title: dynamically created elements automatically get existing styles applied to them. 解决标题中提到的问题:动态创建的元素会自动将现有样式应用于它们。 See this simple example . 看到这个简单的例子

Now looking at your JavaScript, I'd say the issue (besides some errors like multiple declarations of h1 variable) is those dynamic CSS files you're trying to append to the DOM. 现在看一下JavaScript,我要说的是这个问题(除了一些错误,例如h1变量的多个声明)是您要附加到DOM的那些动态CSS文件。 I suggest you have your CSS files included from the start (or have the styles in one CSS file to reduce the number of requests). 建议您从一开始就包含CSS文件(或将样式放在一个CSS文件中,以减少请求数量)。 Also, there is a lot of repetitive code you're writing in each if statement. 另外,每个if语句中都有很多重复的代码。 Here's the same thing optimized (imagine the time related styles included in your CSS already). 这是优化的同一件事(想象一下CSS中已经包含的与时间相关的样式)。

function assignTimeStyle() {
  var currentTime = new Date().getHours(),
      h1 = document.createElement("h1"),
      text,
      style;

  if (0 <= currentTime && currentTime < 5) {
   text = "Good Morning!";
   style = "night";
  }
  if (5 <= currentTime && currentTime < 12) {
    text = "Good Morning!";
    style = "morning";
  }
  if (12 <= currentTime && currentTime < 17) {
    text = "Good Afternoon!";
    style = "day";
  }
  if (17 <= currentTime && currentTime < 22) {
   text = "Good Evening!";
   style = "evening";
  }
  if (22 <= currentTime && currentTime <= 24) {
   text = "Good Evening!";
   style = "night";
  }

  h1.innerHTML = text;
  document.getElementById("time").appendChild(h1);
  document.querySelector("body").classList.add(style);
}

As you see, we're adding a certain style class to the body element based on the time of day. 如您所见,我们将根据一天中的时间将某些样式类添加到body元素中。 That way you can style your elements through the body element in this example. 这样,您可以在此示例中通过body元素设置元素的样式。 A good practise though is to narrow down the parent element as much as possible. 一个好的做法是尽可能缩小父元素的范围。

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

相关问题 如何在Jquery中为文件加载后创建的元素绑定事件? - How to bind events in Jquery for an element created after document load? 将CSS添加到Javascript创建的新文档中 - Adding CSS to new document created by Javascript 在添加到文档 DOM 之前,如何在动态创建的元素上通过 Jquery 更改 css - How to change css via Jquery on dynamically created element before adding to document DOM 向页面加载后动态创建的元素添加Vue.js v-bind:style属性 - Adding a Vue.js v-bind:style attribute to an element that is dynamically created after page load 将事件处理程序(带有参数)添加到使用document.createElement创建的元素 - Adding event handler (with parameters) to element created using document.createElement 将一个元素添加到窗口的文档中是不是有害于它不是创建它的那个? - Is there any harm adding an element to a window's document that is not the one that it was created with? JavaScript 在从 Javascript 加载时创建 HTML 后不添加类 - JavaScript Not Adding Adding Classes After HTML Created on Load from Javascript 向元素添加元素的问题 <body> 页面加载后 - Issue with adding element to <body> after page load 在创建元素后将值添加到DOM元素 - Adding Values to a DOM element after the element has been created GWT-将元素添加到页面后的CSS动画 - GWT - CSS animation after adding element to the page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM