мой размер шрифта localstorage + - ну, в общем, однако, после загрузки исходного размера шрифта + 2 получить строковое значение, например, начальный размер шрифта (16) + 2 = 162. Я думаю, что начальное значение размера должно быть переменной, а не простая строка. Однако исходный размер шрифта, значение localstorage getitem является строкой. После этого он работает хорошо. Как преобразовать начальное значение размера шрифта в переменную? Заранее благодарю за ваш ответ.
<div id="font-size-change">
<span class="font-size-label">font size</span>
<button id="fs_up">+</button>
<span id="fs_write" style="width:15px;"></span>
<button id="fs_down">-</button>
</div>
<script>
$(document).ready(function() { // === Font Size Control =============================================================
var reset = $('#stx').css('fontSize'); // Grab the default font size
var elm = $('#stx'); // Font resize these elements
var size = localStorage.getItem('size');
var size = parseInt(size, 10);
if (size) {
elm.css('font-size', size + 'px');
$( "#fs_write" ).text(size); //
} else {
size = str_replace(reset, 'px', ''); //set the default font size and remove px from the value
$( "#fs_write" ).text(size); //
}
var min = 12; //min
var max = 56; //max
var p = 4; //increase
var m = 4; //decrease
$('#fs_up').click(function() { //Increase font size
if (size <= max) { //if the font size is lower or equal than the max value
size = size + p; //increase the size
elm.css({ //set the font size
'fontSize': size
});
$( "#fs_write" ).text(size); //
localStorage.setItem('size', size);
}
return false; //cancel a click event
});
$('#fs_down').click(function() {
if (size >= min) { //if the font size is greater or equal than min value
size = size - m; //decrease the size
elm.css({ //set the font size
'fontSize': size
});
$( "#fs_write" ).text(size); //
localStorage.setItem('size', size);
}
return false; //cancel a click event
});
$('#fs_write').click(function() { //Reset the font size
elm.css({ //set the default font size
'fontSize': reset
});
size = str_replace(reset, 'px', '');
$( "#fs_write" ).text(size); //
localStorage.setItem('size', size);
});
});
//A string replace function
function str_replace(haystack, needle, replacement) {
var temp = haystack.split(needle);
return temp.join(replacement);
}
</script>
Объяснение:
Это потому, что оператор +
используется как в качестве арифметического оператора (если оба операнда представляют собой числа), так и в качестве оператора конкатенации строк (если хотя бы один из операндов является строкой).
Ваша переменная size
первоначально является номером, поскольку вы используете parseInt
в начале вашего кода, чтобы получить его значение. Но в #fs_write
событий события #fs_write
вы преобразовываете его обратно в строку:
size = str_replace(reset, 'px', ''); // size is now a string because the return value of str_replace is a string
затем, когда #fs_up
щелчок #fs_up
, вы добавляете p
к size
(который теперь является строкой):
size = size + p; // string concatenation is chosen over arithmitic addition because one of the operands (size) is a string
что вызывает проблему.
Решение:
Просто преобразуйте size
в число перед использованием оператора +
используя: Number
, parseInt
или unary +
оператор:
size = +size + p; // using the unary + (now size is a number and p is also a number thus the arithmitic addidtion is chosen over the string concatenation)
// or
size = Number(size) + p; // using Number
Заметки:
#fs_down
прослушиватель событий нажмите doen't вызвать проблемы, потому что -
оператор используется только в качестве arithmitic оператора. Поэтому, когда один или оба операнда являются строкой, он автоматически используется как число ("55" - "10" === 45
но "55" + 10 === "5510"
).size
вам не нужен. Оставьте первый var size =...;
и используйте второй size =...;
без var
.