问题
the problem I am having is that the event handler isn't running when the user types on mobile devices browsers.
My javascript code working like this: When user write someting and press space javascript code automatically adding #(diez) tag for hashtag system. Like if you write: this is test message, javascript code change it like this: #this #is #test #message all after space.
If you check this DEMO on your computer browser (Chrome, Safari, Firefox, Opera) it is working fine.
But if you check this DEMO on your mobile browsers event handler isn't running when you types someting.
$("body").on("keypress","#text", function(e) {
var code = e.charCode || e.keyCode || e.which;
if (charactersX.has(code)) {
var text = $("#text").text();
text = addHashtags(text);
$("#text").text(text);
placeCaretAtEndX(document.querySelector("#text"));
console.log(text);
} else if (forbiddenCharactersX.has(code)) {
e.preventDefault();
console.log("something");
}
});
Full code is HERE.
回答1:
I replaced the $(document).on("keypress", "#textInpu", function(){.....}) part of your code with this and the bug is gone:
$(document).on("textInput", "#text", function(event) {
var code = event.originalEvent.data.charCodeAt(0);
if (charactersX.has(code)) {
// Get and modify text.
var text = $("#text").text();
text = addHashtags(text);
// Save content.
$("#text").text(text);
// Move cursor to the end
placeCaretAtEndX(document.querySelector("#text"));
} else if (forbiddenCharactersX.has(code)) {
e.preventDefault();
}
});
});
This was your issue if you are wondering: keyCode on android is always 229
If there are any bugs after you replace your code with what i provided, please let me know.
来源:https://stackoverflow.com/questions/45270828/keypress-event-is-not-running-on-a-mobile-device