简体   繁体   English

Javascript 记住 combobox 值

[英]Javascript remember combobox value

I currently have 3 combo boxes containing values which apply styles to the page using javascript.我目前有 3 个组合框,其中包含使用 javascript 将 styles 应用于页面的值。

All these styles are applied to a cookie and read on body load, however I'd like to also set the combo box's values to match the applied styles.所有这些 styles 都应用于 cookie 并在身体负载时读取,但是我还想设置组合框的值以匹配应用的 styles。

How do I go about setting a combo box value based on a cookie or applied style?如何根据 cookie 或应用样式设置组合框值?

<select name="sizes" onchange="fontSize(accessibility.sizes.value);"> 
  <option value='-1'>Select</option>
  <option value='10'>Small</option> <option value='12.75'>Medium</option>
  <option value='15.5'>Large</option>
</select>
function fontSize(textSize) { 
  var element = document.getElementById('content'); 
  if (element) {
   element.style.fontSize = textSize + 'px'; 
   createCookie("Font Size", textSize, 365);   
  }
} 

Thanks in advance!提前致谢!

If changing the select is changing the style, first select the relevant value then trigger the onchange.如果改变 select 是改变样式,首先 select 相关值然后触发 onchange。 Notice I changed your script to save the selectedIndex and to apply the change after I set the index.请注意,我更改了脚本以保存 selectedIndex 并在设置索引后应用更改。 Also please notice I pass (this) which the the select object itself and I have added an ID to it.另外请注意我通过(这个)select object 本身,我已经添加了一个 ID。 Lastly I put the medium fontsize as the first item in case people want to reset.最后,我将中等字体大小作为第一项,以防人们想要重置。 Please change that to whatever is the default font size请将其更改为默认字体大小

window.onload=function() {
  var sel = document.getElementById('sizes');// get the select with ID=sizes
 // the following statement gets the select and sets the index to the cookie content if
 // there IS a cookie, else it sets it to 0
 var idx = getCookie("FontSizeIdx") || 0;
  sel.selectedIndex = parseInt(idx,10); // make sure it is a number
 // now call the function and pass the select to it
  fontSize(sel);
}
function fontSize(sel) { // select object is passed as (this) and ends up here as (sel)
  var textSize = sel.options[sel.selectedIndex].value; // get the value
  var element = document.getElementById('content'); // get the content object
  if(element) { // does it exist?
    element.style.fontSize = textSize + 'px'; // set the font size 
    createCookie("FontSizeIdx", sel.selectedIndex, 365); // save the index
  }
} 
<select name="sizes" id="sizes" onchange="fontSize(this);"> 
<option value='12.75'>Select (default is medium)</option> 
<option value='10'>Small</option> 
<option value='12.75'>Medium</option> 
<option value='15.5'>Large</option> 
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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