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

时间:2016-02-12 19:18:42

标签: javascript jquery html

我最近问了一个关于如何使用javascript制作h1并确定innerHTML将是什么的问题。我尝试了每一个答案,但没有一个工作,所以我发布了我的整个代码,以防我有一些需要不同解决方案的东西。

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

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

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

所以我试图在#time id中创建一个h1,它从屏幕开始并动画到中间,然后使用JQuery返回。即使我注释掉所有的CSS和JQuery,h1也不会出现在屏幕上。

请帮助。

2 个答案:

答案 0 :(得分:0)

For one, looks like when you create the h1 it should be like:

document.createElement("H1");

note the capital H. Refer here: createElement

答案 1 :(得分:0)

Next time, please set up an example on JSFiddle so it would be easier for others to tinker with your code example. 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. 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). Also, there is a lot of repetitive code you're writing in each if statement. Here's the same thing optimized (imagine the time related styles included in your CSS already).

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. That way you can style your elements through the body element in this example. A good practise though is to narrow down the parent element as much as possible.