【问题标题】:JSFiddle code not working in my own pageJSFiddle 代码在我自己的页面中不起作用
【发布时间】:2014-01-18 20:32:17
【问题描述】:

我有一些 code that is working in JSFiddle,但我无法在自己的页面中运行。

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 不能。

我尝试用元素的 id 替换 $(this),但仍然没有成功。

【问题讨论】:

  • 您是否将 jquery 库添加到您的 html 中,例如 &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt;
  • 是的,先生,脚本已添加到我的

标签: javascript jquery html css google-chrome


【解决方案1】:

“如果我将代码放入 HTML/JS(在头部链接)”

问题是您将代码放在&lt;head&gt; 中,因此它在输入元素被解析之前运行,因此$('input[type="range"]') 找不到任何元素。

如果您查看 JSFiddle 中的“框架和扩展”选项,您会注意到默认情况下它会将您的 JS 代码放在 onload 处理程序中,因此您的代码在整个页面加载之前不会运行。要使代码在您自己的网页上以相同的方式运行,您需要将其包装在您自己的 onload 处理程序中,或者 - 因为您使用的是 jQuery - 将其包装在 document ready handler 中:

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

或者short form是这样的:

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

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

【讨论】:

  • 您好,感谢您的回答。 javascript 代码当然位于另一个文件中,该文件链接在 中。我已经尝试过你的建议并且它有效!谢谢楼主!
  • 解释得很好!
  • 你是个天才。让我免于不必要地用头撞桌子
【解决方案2】:

您是否确定已将 jQuery 库包含在您的标题中? 对于所有类型的库,请查看 Google 的开发者网站。 https://developers.google.com/speed/libraries/ 这是您要查找的 jQuery 库 - 确保将其放在 JS 文件之前。

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

^ 那应该在您的标题中。 ;)

【讨论】:

  • 您好,谢谢您的回答。是的,我的
  • 哎呀,忽略了你说的话。误会了。
【解决方案3】:
  1. 在您的小提琴编辑器中单击 javaScript+No-Library(pure JS)
  2. 下拉菜单将为您提供选项。
  3. 第三个选项是load-Type- 点击它并选择否wrap-bottom of&lt;head&gt;
  4. 运行你的代码
  5. 享受吧!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多