问题
I have created this toggle switch using css. It works fine on pc browser(both chrome and firefox) but it does not work in mobile browsers i.e if I click on the switches it does not toggle between on and off on mobile browser. Even when I click on the button it is not getting clicked. I read many articles but I did not got any solution with javascript. I also looked into ontouch events but when I use it, the problem still exists.
This is css code for toggle switches:
<style>
.switch input {
display:none;
}
.switch {
display:inline-block;
width:37px;
height:18px;
margin:8px;
transform:translateY(50%);
position:relative;
}
.slider {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
border-radius:15px;
box-shadow:0 0 0 2px #777, 0 0 4px #777;
cursor:pointer;
border:4px solid transparent;
overflow:hidden;
transition:.4s;
}
.slider:before {
position:absolute;
content:"";
width:100%;
height:100%;
background:#777;
border-radius:15px;
transform:translateX(-15px);
transition:.4s;
}
input:checked + .slider:before {
transform:translateX(15px);
background:limeGreen;
}
input:checked + .slider {
box-shadow:0 0 0 2px limeGreen,0 0 2px limeGreen;
}
</style>
This is html code for toggle and button:
<div>
<label class="switch">
<input type="radio" name="subject[]" value="Subject-1" id="Check" onclick="Function()">
<span class="slider"></span>
</label>
</div>
<div>
<label class="switch">
<input type="radio" name="subject[]" value="Others" id="myCheck" onclick="Function1()">
<span class="slider"></span>
</label>
</div><br>
<div id="text" style="display:none">
<input type="text" class="wp-form-control wpcf7-text" style="border-color:#C0C0C0;" placeholder="Mention which subject you want" name="sub"></div>
<br>
<input type="submit" value="Submit" name="submit" class="wpcf7-submit"><br><br>
</div>
This is javascript part for onclick function:
document.getElementById("myCheck").addEventListener("touchstart", Function);
function Function() {
if (document.getElementById('myCheck').checked) {
document.getElementById('text').style.display = 'block';
}
else document.getElementById('text').style.display = 'none';
}
Any javascript solution for this? What changes should I make? What is going wrong with this code?
回答1:
Did you try to not use hoisting, not every engine are efficient with that. I propose you to change your javascript to :
document.getElementById("myCheck").addEventListener("touchstart", function() {
if (document.getElementById('myCheck').checked) {
document.getElementById('text').style.display = 'block';
}
else document.getElementById('text').style.display = 'none';
});
Also there is myCheck and Check in your html, be sure to test the right thing.
来源:https://stackoverflow.com/questions/51077832/buttons-and-toggle-switch-does-not-work-in-mobile-browser