如何在屏幕宽度变化时激活.insertBefore?

时间:2016-11-24 00:07:02

标签: javascript jquery

我有这个片段,如果屏幕宽度低于767px,它会将辅助包装器的位置切换到主包装器上方。这很好用,但它只适用于刷新。当屏幕宽度改变时,如何让它自动工作?

谢谢!这里总新手。

#define __ATTR_RW(_name) __ATTR(_name, (S_IWUSR | S_IRUGO),             \
                         _name##_show, _name##_store)

4 个答案:

答案 0 :(得分:2)

好像你正在使用jquery所以我推荐使用.resize()方法。

https://api.jquery.com/resize/

每当调整窗口大小时都会触发。你可以让它做任何你需要的事情。

$(window).resize(function(){
    If (myWindow.width() >= windowThreshold){
        //do all the things...
    }
});

答案 1 :(得分:1)

window.addEventListener('resize', function() {
// do something with screen width
});

或使用jQuery:

$(window).on('resize', function() {
    // do something with screen width
})

答案 2 :(得分:1)

我推荐使用.resize()方法,因为您使用的是JQuery。无论何时调整窗口大小,都会调用此方法。

现在,您可以添加这样的代码。

var windowThreshold = 767;

$(window).resize(function() {
  if ($(window).width() < windowThreshold + 1) {
    // do something with $(window).width()
    $("#log").append("<div>The window size is " + $(window).width() + "px</div>");
    $('#secondary').insertBefore('#primary');
  }
});
#primary {
  background-color: red;
}

#secondary {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="log"></div>
<div id="primary">primary</div>
<div id="secondary">secondary</div>

您也可以使用.on("resize", function() {})

$(window).on('resize', function() {
  if ($(window).width() < windowThreshold + 1) {
    // do something with $(window).width()
    $("#log").append("<div>The window size is " + $(window).width() + "px</div>");
    $('#secondary').insertBefore('#primary');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 3 :(得分:1)

我知道这有一个公认的答案,但只是为了记录,你可以让CSS通过使用媒体查询和flexbox来完成工作。

import wave
import struct
import numpy as np
import matplotlib.pyplot as plt 

sound_file = wave.open('Audio_1.wav', 'r') 
file_length = sound_file.getnframes()
sound = np.zeros(file_length)
for i in range(file_length):
    data = sound_file.readframes(1)
    data = struct.unpack("<h", data)
    sound[i] = int(data[0])
sound = np.divide(sound, float(2**15)) # Normalized data range [-1 to 1]
#print sound #vector corresponding to  audio signal containing audio samples
Ap = np.pad(sound, (0,int(np.ceil(len(sound) / 2205.)) * 2205 - len(sound)), 'constant', constant_values=0) # Padding of the sound samples so that the input is a multiple of 2205(window Length)
Apr = Ap.reshape((len(Ap) // 2205, 2205)) 
Apr.shape
array1=(Apr ** 2).sum(axis=1) #Record Sum of Squares of the amplitude of  the signal  falling within that window
print array1
#print len(array1)
threshold =1103.4
result= np.array(filter(lambda x: x>= threshold, array1)) #filtering elements below set threshold
print result 

print len(result)
print np.where(array1>1103.4) # finding starting index of the elements.
np.fft.fft()