Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

javascript - How do I put codes from jsfiddle.net into my website?

I’ve been trying to create a little box at the bottom of my webpage which will expand / pop-up when scrolled over and then close again when the mouse moves away.

I found this post with a link to jsfiddle.net (which I have been fiddling about with) and have created something that works exactly like I want when viewed on JSFiddle. But I can’t get it to run when I pop it on my website (I think it may have something to do with the onLoad setting but I’m really not sure).

This is what I have created in JSFiddle:

JavaScript

$('#box').hover(function() {
  $(this).animate({
    height: '220px'
  }, 150);
}, function() {
  $(this).animate({
    height: '20px'
  }, 500);
});

CSS

#box {
  position: absolute;
  width: 300px;
  height: 20px;
  left: 33%;
  right: 33%;
  min-width: 32%;
  bottom: 0;
  background-color: #000000;
}

HTML

<div id="box"></div>

This works fine in JSFiddle but not when I try and insert the code into my files and link them together. If I change the drop down box in JSFiddle from onLoad or onDomReady to anything else, it stops working, but the code doesn’t change. So I think I have to add something else somewhere for that.

As you can probably guess, I am a complete novice when it comes to JavaScript so I’m positive that I’m not doing something right.

Could someone please tell me how to save the JavaScript code and link it to my webpage so it will work exactly like it is on JSFiddle?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are running this code immediately, rather than waiting for the DOM to be ready. This means that the element #box may not exist yet.

jsFiddle automates this process to make your code cleaner. You need to do it yourself when you put the code into your own website. It is very easy: you just need to put your code into a callback to the ready event on the document:

$(document).ready(function() {
    // put your Javascript here
});

or, a shortcut version:

$(function(){
    // put your Javascript here
});

These are semantically and functionally equivalent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...