代码在我自己的页面中不起作用

代码在我自己的页面中不起作用

本文介绍了JSFiddle 代码在我自己的页面中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 代码在 JSFiddle 中运行,但我无法运行我自己的页面.

I have some code that is working in JSFiddle but which I can't get to run in my own page.

HTML

<body style="background-color: #000000">
  <form oninput="amount.value=range.value" style="color:#1ec2c5;">
  <output name="amount" for="range">2</output><a> KM</a>
  <input type="range" name="range" min="1" max="9" step="1" value="2" id="test">
</body>

CSS

input[type="range"]{
  -webkit-appearance: none;
  -moz-apperance: none;
  border-radius: 6px;
  width: 225px;
  height: 6px;
  border: 2px solid #eceef1;
  outline:none;
  background-image: -webkit-gradient(
    linear,
    left top,
    right top,
    color-stop(0.15, #eceef1),
    color-stop(0.15, #0c0d17)
  ); }

input[type='range']::-webkit-slider-thumb {
  -webkit-appearance: none !important;
  background-color: #1ec2c5;
  border: 3px solid #000000;
  height: 25px;
  width: 25px;
  border-radius: 20px;}

JavaScript

$('input[type="range"]').change(function () {
var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));

$(this).css('background-image',
            '-webkit-gradient(linear, left top, right top, '
            + 'color-stop(' + val + ', #eceef1), '
            + 'color-stop(' + val + ', #0c0d17)'
            + ')'
            );
});

如果我将代码放入 HTML/JS(在 head 中链接)/CSS(在 head 中链接)文件中,CSS 可以运行,但 JavaScript 不起作用.

If I take the code and put in the HTML/JS (linked in head)/CSS (linked in head) files, the CSS works but the JavaScript does not.

我已经尝试用元素的 id 替换 $(this) 但仍然没有运气.

I've tried replacing $(this) with the id of the element but still no luck.

推荐答案

问题是你已经把你的代码放在 中,所以它在输入元素被解析之前运行,然后 $('input[type="range"]') 未找到任何元素.

The problem is that you've put your code in the <head>, so it runs before the input elements have been parsed and so then $('input[type="range"]') finds no elements.

如果您查看 JSFiddle 中的框架和扩展"选项,您会注意到它默认将您的 JS 代码放在 onload 处理程序中,因此您的代码直到整个页面已加载.要使代码在您自己的网页上以相同的方式运行,您需要将其包装在您自己的 onload 处理程序中,或者 - 因为您使用的是 jQuery - 将其包装在 文档就绪处理程序:

If you look at the "Frameworks & Extensions" options in JSFiddle, you'll notice that it puts your JS code in an onload handler by default, so your code doesn't run until the whole page has loaded. For the code to behave the same way on your own web page you'd need to wrap it in an onload handler of your own, or - since you're using jQuery - wrap it in a document ready handler:

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

或者简写是这样的:

$(function() {
    // your code here
});

或者在页面末尾包含您的脚本,以便它在尝试操作的元素被解析之后运行.

Or include your script at the end of the page, so that it runs after the elements it tries to manipulate have been parsed.

这篇关于JSFiddle 代码在我自己的页面中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 15:46