如何将来自 jsfiddle.net 的代码放入我的网站? [英] How do I put codes from jsfiddle.net into my website?

查看:33
本文介绍了如何将来自 jsfiddle.net 的代码放入我的网站?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在我的网页底部创建一个小框,它会在滚动时展开/弹出,然后在鼠标移开时再次关闭.

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.

我发现了这个帖子 带有到 jsfiddle.net 的链接(我一直在摆弄它)并创建了一些在 JSFiddle 上查看时完全符合我想要的东西.但是当我在我的网站上弹出它时我无法让它运行(我认为这可能与 onLoad 设置有关,但我真的不确定).

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

这是我在 JSFiddle 中创建的:

This is what I have created in JSFiddle:

$('#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>

这在 JSFiddle 中工作正常,但当我尝试将代码插入我的文件并将它们链接在一起时就不行了.如果我将 JSFiddle 中的下拉框从 onLoadonDomReady 更改为其他任何内容,它会停止工作,但代码不会更改.所以我想我必须为此在某处添加其他东西.

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.

正如您可能猜到的那样,我在 JavaScript 方面完全是个新手,所以我确信我做的事情不对.

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.

有人可以告诉我如何保存 JavaScript 代码并将其链接到我的网页,这样它就可以像在 JSFiddle 上一样工作吗?

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?

推荐答案

您正在立即运行此代码,而不是等待 DOM 准备就绪.这意味着元素 #box 可能还不存在.

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 自动执行此过程以使您的代码更简洁.当您将代码放入自己的网站时,您需要自己完成.这很简单:您只需将代码放入 ready 事件的回调中在 document 上:

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

或者,一个快捷版本:

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

这些在语义和功能上是等效的.

These are semantically and functionally equivalent.

这篇关于如何将来自 jsfiddle.net 的代码放入我的网站?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆