I need some help with this JavaScript code, I'm all new to using javascript so when I get stuck it gets annoying. What I'm trying to do is change the image displayed on my nav bar when on small screens (mobiles) because the nav bar color changes. What I have e up with so far by searching online and some playing only works when the screen size is manually reduced and then the image changes like it should. However I want it to load in this state as well and thats where I am stuck.
$(window).on('resize', function(){
var win = $(this);
if (win.width() < 768) {
$(".navbar-brand img").attr('src', 'img/icons/logowhite.png');
} else {
$(".navbar-brand img").attr('src', 'img/icons/logodark.png');
}});
Could this be done in the css instead is also a question I have?
I need some help with this JavaScript code, I'm all new to using javascript so when I get stuck it gets annoying. What I'm trying to do is change the image displayed on my nav bar when on small screens (mobiles) because the nav bar color changes. What I have e up with so far by searching online and some playing only works when the screen size is manually reduced and then the image changes like it should. However I want it to load in this state as well and thats where I am stuck.
$(window).on('resize', function(){
var win = $(this);
if (win.width() < 768) {
$(".navbar-brand img").attr('src', 'img/icons/logowhite.png');
} else {
$(".navbar-brand img").attr('src', 'img/icons/logodark.png');
}});
Could this be done in the css instead is also a question I have?
Share Improve this question edited Apr 14, 2015 at 0:36 rob12345 asked Apr 14, 2015 at 0:24 rob12345rob12345 291 silver badge8 bronze badges3 Answers
Reset to default 3demo in fiddle
JS
function resize(){
if ($(window).width() < 768) {
$(".navbar-brand img").attr('src', 'https://www.google./images/srpr/chrome_ntp_white_logo2.png');
} else {
$(".navbar-brand img").attr('src', 'https://www.google./images/srpr/logo11w.png');
}
}
resize();
$(window).on('resize', resize);
HTML
<div class='navbar-brand'>
<img src=''/>
</div>
Could this be done in the css instead is also a question I have?
It is far easier and better in CSS than in Javascript!
Read this question: Responsive design with media query : screen size?
Code to change background image with CSS
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
div {
background-image: url("img/icons/logowhite.png");
}
}
@media only screen and (min-device-width : 768px) {
div {
background-image: url("img/icons/logodark.png");
}
}
You are talking about mobile devices. Are you maybe trying this code in a mobile or a simulator?? You said the code works when resizing the screen manually. If you refer to the resize event on mobiles, maybe it will not work if you dont look at the orientation change event.
Check if this answer helps you
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745272948a4619860.html
评论列表(0条)