简体   繁体   中英

How to change a javascript variable with HTML?

I am making a chrome extension which adds icons to certain URLs, so I would like to make a slider to adjust the size of the icon in the popup.html .

The HTML of the slider looks like this:

<div class="slidecontainer">
   <input type="range" min="1" max="3" value="2" class="slider" id="myRange">
</div>

But for the slider to work, it needs some javascript code.

In the javascript file, I made a variable called size . I need the javascript to change the size variable according to the position of the slider.

var size = "/images/icon16.png";
var imageURL = "chrome-extension://" + chrome.i18n.getMessage("@@extension_id") + size;

So I am thinking of a script that checks for myRange , and if it is 1 , 2 , or 3 , it sets size to corresponding string:

  1. "/images/icon16.png"
  2. "/images/icon48.png"
  3. "/images/icon128.png"

The catch is that I don't know how to implement this in my code, so any help or explanation would mean the world to me...

You could save your strings in an array:

var myPaths = [
  "/images/icon16.png",
  "/images/icon48.png",
  "/images/icon128.png"
]

And access your slider input like this:

var slider = document.getElementById("myRange");

so that slider.value will be the value of the input .

You could listen out for the change event on the slider, and then set your size variable accordingly.

Full code:

var myPaths = [
  "/images/icon16.png",
  "/images/icon48.png",
  "/images/icon128.png"
];

var size = "/images/icon16.png";
var slider = document.getElementById("myRange");

slider.addEventListener("change", updateSize);

function updateSize() {
  size = myPaths[slider.value - 1];
}

In short: document.getElementById("myRange").value; .

You can read more about sliders and getting the value of the slider here . If you want to get the value every time the slider is utilised:

document.getElementById("myRange").addEventListener("input", (evt) => {
  console.log(evt.target.value);
})
  1. Attach an onchange event listener to the input tag.
  2. Declare enum as follows:
let enum = {
  1: "/images/icon16.png",
  2: "/images/icon48.png",
  3: "/images/icon128.png"
} 
  1. Write something like this in the callback:
var size,
    imageURL;

let enum = {
  1: "/images/icon16.png",
  2: "/images/icon48.png",
  3: "/images/icon128.png"
} 

let inputrange = document.querySelector('input[type=range]');

inputrange.addEventListner("change", function() {
  size = enum[inputrange.value];
  imageURL = `chrome-extension://${chrome.i18n.getMessage("@@extension_id") + size}` ;
}) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM