我目前有3个组合框,其中包含使用javascript将样式应用于页面的值。
所有这些样式都应用于cookie并读取正文加载,但我还想设置组合框的值以匹配应用的样式。
如何根据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);
}
}
提前致谢!
答案 0 :(得分:0)
如果更改选择正在更改样式,请先选择相关值然后触发onchange。注意我更改了脚本以保存selectedIndex并在设置索引后应用更改。另请注意我传递(this)选择对象本身,我已经添加了一个ID。最后,我将中等字体大小作为第一项,以防人们想要重置。请将其更改为默认字体大小
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>