我有一些 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(链接在头部)/CSS(链接在头部)文件中,CSS 可以工作,但 JavaScript 不会。
我尝试用元素的 id 替换 $(this)
但仍然没有成功。
最佳答案
"If I take the code and put in the HTML/JS (linked in head)"
问题是您已将代码放在 <head>
中, 所以它在输入元素被解析之前运行,然后 $('input[type="range"]')
找不到任何元素。
如果您查看 JSFiddle 中的“框架和扩展”选项,您会注意到它将您的 JS 代码放在 onload
中。默认情况下处理程序,因此您的代码在整个页面加载之前不会运行。为了使代码在您自己的网页上以相同的方式运行,您需要将其包装在 onload
中。您自己的处理程序,或者 - 因为您使用的是 jQuery - 将其包装在 document ready handler 中:
$(document).ready(function() {
// your code here
});
或者 short form是这样的:
$(function() {
// your code here
});
或者在页面末尾包含您的脚本,以便它在它尝试操作的元素被解析后运行。
关于javascript - JSFiddle 代码在我自己的页面中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816908/